JD.*_*JD. 6 linq-to-entities many-to-many entity-framework left-join
我在查询Linq To Entities中的多对多关系时遇到问题.我基本上尝试使用Linq复制此查询:
Select *
FROM Customer
LEFT JOIN CustomerInterest ON Customer.CustomerID = CustomerInterest.CustomerID
LEFT JOIN Interest ON CustomerInterest.InterestID = Interest.InterestID
WHERE Interest.InterestName = 'Football'
Run Code Online (Sandbox Code Playgroud)
我环顾网络并没有找到任何合适的例子来说明这一点.我最接近的是:
List<Customer> _Customers = (from _LCustomers in _CRM.Customer.Include("CustomerInterest.Interest")
where _LCustomers.CustomerInterest.Any(x => x.Interest.InterestName == "Football")
select _LCustomers).ToList();
Run Code Online (Sandbox Code Playgroud)
这样做的问题是,如果客户有多个兴趣而其中一个是"足球",则返回所有这些兴趣.我也看过All()有逆问题,即只有他们有一个兴趣才会返回,而且只有足球,如果他们有两个,而其中一个不是足球,则不返回任何东西.
有人有任何想法吗?
试试这个,
var result = from c in ctx.Customer
from i in c.Interest
where i.InterestName == "Football"
select c;
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助,
射线.
我不确定你想获得什么。具有客户兴趣和兴趣的客户列表?只需根据客户的兴趣开始查询即可。
context.CustomerInterest.
Where(ci => ci.Interest.InterestName == "Football").
Select(ci => new
{
Customer = ci.Customer,
CustomerInterest = ci,
Interest = ci.Interest
});
Run Code Online (Sandbox Code Playgroud)
但这是非常多余的。为什么不直接获取匹配的客户兴趣呢?
IEnumerable<CustomerInterest> customerInterests = context.CustomerInterest.
Where(ci => ci.Interest.InterestName == "Football");
Run Code Online (Sandbox Code Playgroud)
您仍然可以访问其他信息,而无需显式存储。
foreach (CustomerInterest customerInterest in customerInterests)
{
DoSomething(customerInterest);
DoSomething(customerInterest.Customer);
DoSomething(customerInterest.Interest);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18639 次 |
| 最近记录: |