【问题标题】:C# Entity Framework: Linq Filter on GrandChildren and Conduct a Select on the Parent with AttributesC# 实体框架:Linq 过滤 GrandChildren 并使用属性对父级进行选择
【发布时间】:2020-06-21 22:31:18
【问题描述】:

我们公司目前正在使用Entity Framework Net Core 2.2 with Sql Server

试图找到所有购买了某个产品输入参数的不同客户。 编写以下 EF Linq 查询以获取不同的客户。

后来另一个问题出现了,我们如何获得客户的更多(导航)属性? Include应该放在Where之前还是之后?有关系吗?运行 SQL Profiler 时,它注意到查询没有任何区别。我只是想确定在某些情况下 Include here 的位置是否重要?

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

原解决方案: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());

另一个问题来了,我们需要获取更多的客户(导航)属性。

备选方案 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());

备选方案 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)

【问题讨论】:

  • 正确的术语是“财产”。在 C#/.NET 中,“属性”是别的东西
  • 根据此观察,我编辑了问题以使用短语“(导航)属性)”而不是属性。 (留下这个,让未来的读者知道你不是在编造东西@pinkfloyd)

标签: c# .net entity-framework linq .net-core-2.2


【解决方案1】:

在这种特定情况下,它可能无关紧要。

由于c#“Include”是关于生成的sql的SELECT和JOIN。

但是,您不想将“没关系”用作笼统的陈述。

请参阅下面的答案(以及总体问题和其他答案)。

Does the order of LINQ functions matter?

当您开始添加诸如 Where 和 OrderBy 之类的内容时,操作的顺序可能很重要。

总是查看生成的 sql 并问自己“看起来合理吗”? (你已经从你的问题中做到了:) ..我主要为未来的读者提到这一点)

所以在这种特定情况下,这是一种偏好。我通常把 .Where 最后的。所以你的第一个例子会符合我的个人喜好。

对于一些“进一步调查”,请查看以下内容:https://weblogs.asp.net/dixin/introducing-linq-3-waht-is-functional-programming

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-10-10
  • 2016-08-03
  • 1970-01-01
  • 2011-08-23
  • 1970-01-01
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多