当前位置: 首页 > news >正文

使用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 进行左关联查询。


http://www.mrgr.cn/news/24901.html

相关文章:

  • 真正解决微信截图卡住(假死)
  • 【AcWing】快速排序的Go实现
  • Python中的类(一)
  • 【PyQt6 应用程序】在用户登录界面实现密码密文保存复用
  • 误删?损坏?别怕!固态硬盘数据恢复工具助你轻松找回
  • UE5——笔刷Brush工具
  • Qt第三课 ----------按钮的控件属性
  • 【移动端】Flutter与uni-app:全方位对比分析
  • 队列的详细操作
  • 采用qt做一个命令行终端
  • YoloV10改进策略:上采样改进|动态上采样|轻量高效,即插即用(适用于分类、分割、检测等多种场景)
  • 128. 最长连续序列-LeetCode(C++)
  • Day7 | Java框架 | SpringMVC
  • 633. 平方数之和-LeetCode(C++)
  • 认识人工智能(AI,Artificial Intelligence)
  • 多文件编程实现链表创建,插入,输出(上)
  • 期望极大算法(Expectation Maximization Algorithm,EM)
  • C++ STL之set和unordered_set
  • STM32点亮第一个LED
  • Redis 入门 - C#|.NET Core客户端库六种选择