使用Linq进行多表查询(C#)

本文材料

创建一个学生 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.student
    join scs in _context.sc on students.sno equals scs.sno
    into studentScs
    from scs in studentScs.DefaultIfEmpty()
    join courses in _context.course on   scs.cno equals courses.cno
    into scCorse
    from 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 进行左关联查询。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值