Entity Framework Classic Include

Entity Framework Classic  Include

The Include method lets you add related entities to the query result.

In EF Classic, the Include method no longer returns an IQueryable but instead an IncludeDbQuery that allows you to chain multiple related objects to the query result by using the AlsoInclude and ThenInclude methods.

ctx.Customers
	.Include(customer => customer.Orders)
		.ThenInclude(order => order.OrderDetails)
		.ThenInclude(orderDetail => orderDetail.Product)
			.AlsoInclude(product => product.Category)
			.AlsoInclude(product => product.Supplier)
	.ToList();

Try it: NET Core | NET Framework

Note

  • If you want to include items from the same level, use AlsoInclude
  • If you want to include items from the next level, use ThenInclude
Limitation

DbQuery

Chaining includes only work if the first include call is from a DbQuery. If you used some LINQ and the query is currently an IQueryable, you can use the method AsDbQuery to tell the compiler that's a DbQuery. This restriction is currently required to avoid some side impact with queries that are not directly using the DbQuery class.

ctx.OrderDetails
	.Where(orderDetail => orderDetail.Quantity > 1)
	.AsDbQuery()
	.Include(orderDetail => orderDetail.Product)
		.AlsoInclude(product => product.Category)
		.AlsoInclude(product => product.Supplier)
	.ToList();

Try it: NET Core | NET Framework

It's planned to remove this limitation.

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-08-17 游戏术语
2021-08-17 the user account is not authorized for remote login
2020-08-17 乐刻健身房 间隔天数
2015-08-17 Linq打印
2015-08-17 .net framework client profile
2015-08-17 Resharper中注释代码的快捷键
2015-08-17 What does the number on the visual studio solution icon represent?
点击右上角即可分享
微信分享提示