C# Entity Framework: Linq Filter on GrandChildren and Conduct a Select on the Parent with Attributes

烈酒焚心 提交于 2020-06-29 03:42:31

问题


Our company is currently using Entity Framework Net Core 2.2 with Sql Server

Trying to find all Distinct customers who purchased a certain Product Input Parameter . The following EF Linq query was written to get the distinct Customers.

Later another question came up, how do we get more (navigation) properties of customer? Should Include be placed Before the Where or After the Where? Does it matter? When running the SQL Profiler, it noted no difference in the queries. I just wanted to be sure in some cases does the location of Include here matter?

select distinct c.customerName
from dbo.customer customer
inner join dbo.Transactions transaction
    on transaction.customerid = customer.customerid
inner join dbo.Purchases purchases
    on purchases.PurchaseId = transaction.PurchaseId
inner join dbo.Product product 
    on transaction.ProductId = product.ProductId
where tra.BKProduct = @ProductInput

Original Solution: C# Entity Framework: Linq Filter on GrandChildren and Conduct a Select on the Parent

var customerData = db.Customer
                      .Where(p => p.Transactions.SelectMany(c => c.Purchases).Select(gc => gc.Product.Where(gc => gc.BKProduct == ProductInput).Any());

Another question came up, we need to get more (navigation) properties of Customer.

Alternative 1:

var customerData = db.Customer
                      .Include(c=>c.CustomerType)
                      .Include(c=>c.CustomerAddress)
                      .Where(p => p.Transactions.SelectMany(c => c.Purchases).Select(gc => gc.Product.Where(gc => gc.BKProduct == ProductInput).Any());

Alternative 2:

var customerData = db.Customer
                      .Where(p => p.Transactions.SelectMany(c => c.Purchases).Select(gc => gc.Product.Where(gc => gc.BKProduct == ProductInput).Any())
                      .Include(c=>c.CustomerType)
                      .Include(c=>c.CustomerAddress)

回答1:


In this specific case, it probably does not matter.

Since c# "Include" is about the SELECT and the JOIN of the generated sql.

However, you do not want to use the "it does not matter" as a blanket statement.

See here answer below (and overall question and other answers).

Does the order of LINQ functions matter?

When you start putting in things like Where and OrderBy, the order-of-the-operations can matter.

Always look at the generated sql and ask yourself "does it look reasonable"? (Which you already did from your question :) ..I mention primarily this for future readers)



来源:https://stackoverflow.com/questions/62505149/c-sharp-entity-framework-linq-filter-on-grandchildren-and-conduct-a-select-on-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!