EF Core使用Include和join,以及Include和ThenInclude区别

本文探讨了EF Core中Join()和Include()两种表连接方式。Join()适用于无外键关系的连接,允许自定义连接条件,而Include()依赖外键并自动包含相关数据。Include()在多级数据获取时,需配合ThenInclude()使用,以避免低效的数据库查询。文章通过示例说明了如何使用这两种方法,并强调了效率问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

EF Core使用Include和join

在EF中表连接常用的有Join()和Include(),两者都可以实现两张表的连接,但又有所不同。

例如有个唱片表Album(AlbumId,Name,CreateDate,GenreId),表中含外键GenreId连接流派表Genre(GenreId,Name)。每个唱片归属唯一一个流派,一个流派可以对应多个唱片。

1.Join():

两表不必含有外键关系,需要代码手动指定连接外键相等(具有可拓展性,除了值相等,还能指定是>,<以及其他对两表的相应键的关系),以及结果字段。

  • 那么可以这么写两个表的连接:
var wholeRecord = dc.Album.Join(dc.Genre, a => a.GenreId, g => g.GenreId, (a, g) => new { a.AlbumId,a.Name,g.GenreId,g.Name;

这样就选取除了两表的AlbumId,Name,GenreId,Name。

2.Include():

两表必须含有外键关系,只需要指定键名对应的类属性名即可,不需指定结果字段(即全部映射)。默认搜索某表时,不会顺带查询外键表,直到真正使用时才会再读取数据库查询;若是使用 Include(),则会在读取本表时把指定的外键表信息也读出来。

  • 那么可以这么写两个表的连接:
Summary Entity Framework Core in Action teaches you how to access and update relational data from .NET applications. Following the crystal-clear explanations, real-world examples, and around 100 diagrams, you'll discover time-saving patterns and best practices for security, performance tuning, and unit testing. Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications. About the Technology There's a mismatch in the way OO programs and relational databases represent data. Enti ty Framework is an object-relational mapper (ORM) that bridges this gap, making it radically easier to query and write to databases from a .NET application. EF creates a data model that matches the structure of your OO code so you can query and write to your database using standard LINQ commands. It will even automatically generate the model from your database schema. About the Book Using crystal-clear explanations, real-world examples, and around 100 diagrams, Entity Framework Core in Action teaches you how to access and update relational data from .NET applications. You'l start with a clear breakdown of Entity Framework, long with the mental model behind ORM. Then you'll discover time-saving patterns and best practices for security, performance tuning, and even unit testing. As you go, you'll address common data access challenges and learn how to handle them with Entity Framework. What's Inside Querying a relational database with LINQ Using EF Core in business logic Integrating EF with existing C# applications Applying domain-driven design to EF Core Getting the best performance out of EF Core Covers EF Core 2.0 and 2.1
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值