c# - Creating anonymous object from linq select new
问题描述
I have a code that sort of solves my need of imitating an Include with a filter, but there is one part I don't fully understand what it does and why it's working.
I need to retrieve a customer with it's orders. In the db, the orders can be deleted so I'm only interested in bringing active orders. I disabled lazy loading, so I add the Include at the begining of the query.
var customer = (from c in Customers
.Include(c => c.Orders)
where c.CustomerId == customerId
select new {
Customer = c,
Orders = from o in c.Orders
where o.DeletedDate == null
select o
}).ToArray().Select(x => x.Customer).FirstOrDefault();
If at the end I'm doing the Select(x => x.Customer)
, effectively retrieving only the Customer from the anonymous object, how is that the Orders property inside Customer is updated with the value I set in Orders in the second line of the anonymous object creation?
If I don't include the second part in the anonymous object constructor, the Customer object has no value inside Orders.
解决方案
EF 不支持条件包含。ObjectQuery.Include(...) 将包括全部或全部。
调用 ToArray() 时,EF 尝试执行称为关系修复的操作。当您同时加载客户和订单时,EF 确保它们自动链接,这意味着匹配的订单存在于 Customer.Orders 中。
参考链接:
https://blogs.msdn.microsoft.com/alexj/2009/10/12/tip-37-how-to-do-a-conditional-include/
推荐阅读
- android - 如何在flutter中将第三方android库导入java文件
- c# - 将边框添加到仅在聚焦时可见的选择器?
- c# - 创建数据库表不起作用 -> 存在,无法打开
- vb.net - 接收 Http Post 请求 VB.Net
- regex - 如何在 VS Code 中的特定文件中搜索?
- python - Python:用 ssh 连接替换 shell 管道并在 python 变量中取回结果
- firebase - 如何使用 Firebase SMTP 设置 GSuite 域
- ios - XCTestCase 错误
- java - 当活动发生变化时,BluetoothSocket.getInputStream() 会导致 NullPointerException
- ios - iOS 在睡眠模式下使用 iBeacon 数据包终止应用程序唤醒