本文材料
创建一个学生 Student 模型
public class Student {public string sno { get; set; }public string sname { get; set; }public string ssex { get; set; }public DateTime? birthday { get; set; }public string specialty { get; set; }public string grade { get; set; } }
创建一个成绩 sc模型
public class sc {public string sno { get; set; }public string cno { get; set; }public byte? score { get; set; } }
创建一个课程 course模型
public class course {public string cno { get; set; }public string cname { get; set; }public byte? classhour { get; set; }public byte? credit { get; set; } }
创建一个 StudentScCourse模型,用于多表关联查询
public class StudentScCourse {public string sno { get; set; }public string sname { get; set; }public string cno { get; set; }public string? cname { get; set; }public byte? score { get; set; } }
创建上下文 DbContext类
public class AppDbContext : DbContext {public AppDbContext(DbContextOptions<AppDbContext> options) : base(options){}public DbSet<Student> student { get; set; }public DbSet<sc> sc { get; set; }public DbSet<course> course { get; set; }// 使用 HasKey()方法给 sc表创建双主键protected override void OnModelCreating(ModelBuilder modelBuilder){modelBuilder.Entity<sc>().HasKey(e => new { e.sno, e.cno });} }
一、Linq单表查询
简单查询
_context.student;
单条件数据过滤
_context.student.Where(n => n.sno == sno.Trim()).FirstOrDefault();
多字段模糊匹配数据过滤
if (!string.IsNullOrEmpty(keyword)) {return _context.student.Where(n => n.sno.Contains(keyword) ||n.sname.Contains(keyword) ||n.ssex.Contains(keyword) ||n.specialty.Contains(keyword) ||n.grade.Contains(keyword)); }
二、Linq多表查询
IEnumerable<StudentScCourse> result =from students in _context.studentjoin scs in _context.sc on students.sno equals scs.snointo studentScsfrom scs in studentScs.DefaultIfEmpty()join courses in _context.course on scs.cno equals courses.cnointo scCorsefrom courses in scCorse.DefaultIfEmpty()// 使用 where进行数据过滤where students.sno.Contains(keyword) || students.sname.Contains(keyword) ||scs.cno.Contains(keyword) ||courses.cname.Contains(keyword) ||keyword == null// 使用 select 关键字来选中查询的结构select new StudentScCourse{sno = students.sno,sname = students.sname,cno = scs.cno,cname = courses.cname,score = scs.score};
在查询时,可以使用 join函数进行多表关联查询;可以使用 join into 进行左关联查询。