欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > 使用Linq进行多表查询(C#)

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

2025/5/15 18:02:30 来源:https://blog.csdn.net/qq_61709335/article/details/142155306  浏览:    关键词:使用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.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 进行左关联查询。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词