首页 > 解决方案 > 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.

标签: c#linq

解决方案


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/


推荐阅读