gpt4 book ai didi

c# - 离开加入 Linq?

转载 作者:太空狗 更新时间:2023-10-29 22:18:10 25 4
gpt4 key购买 nike

SO 上已经有很多关于 Linq 中的左连接的问题,我看过的问题都使用 join 关键字来实现所需的结果。

这对我来说没有意义。假设我有表 CustomerInvoice,它们由 Invoice 上的外键 CustomerID 链接。现在我想运行一份包含客户信息以及所有发票的报告。 SQL 将是:

select c.*, i.*
from Customer c
left join Invoice i on c.ID = i.CustomerID

根据我在 SO 上看到的答案,人们大多建议:

var q = from c in Customers
join i in Invoices.DefaultIfEmpty() on c.ID equals i.CustomerID
select new { c, i };

我真的不明白这怎么可能是唯一的方法。 CustomerInvoice 之间的关系已经由 LinqToSQL 类定义;为什么我必须为 join 子句重复它?如果我想要一个内部联接,它会简单地是:

var q = from c in Customers
from i in c.Invoices
select new { c, i };

不指定连接字段!

我试过:

var q = from c in Customers
from i in c.Invoices.DefaultIfEmpty()
select new { c, i };

但这只给了我与内部连接相同的结果。

没有更好的方法吗?

最佳答案

虽然关系已经定义(在数据库和 .dbml 标记中),运行时无法自动确定它是否应该使用该关系。

如果对象模型中有两个关系(Person 有 Parents 和 Children,两者都与其他 Person 实例有关系)怎么办?虽然案例可能是特殊案例,但这会使系统更加复杂(因此会有更多错误)。请记住,在 SQL 中您会重复关系的规范。

请记住,索引和键是实现细节,而不是构成关系模型基础的关系代数的一部分。

如果你想要一个 LEFT OUTER JOIN 那么你需要使用“into”:

from c in Customers
join i in Invoices on i.CustomerId equals c.CustomerId into inv
...

inv 的类型为 IEnumerable<Invoivce> ,可能没有实例。

关于c# - 离开加入 Linq?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1092562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com