数据库中有三个相关的表。倡导者,供应商和Advocate_Vendor。
Advocate_Vendor表是多对多链接,有一个vendorId和一个advocateId。
我的最终目标是找回一个List<Advocate>
对象......一组属于一个供应商的拥护者。我写了这个:
var list = new List<Advocate>();
foreach (var vendorAdvocates in db.Advocate_Vendors)
{
if (vendorAdvocates.VendorId == vendorId)
{
list.Add(db.Advocates.SingleOrDefault(a => a.AdvocateId == vendorAdvocates.AdvocateId));
}
}
然后这个:
var list = (from vendorAdvocates in db.Advocate_Vendors
where vendorAdvocates.VendorId == vendorId
select db.Advocates.SingleOrDefault(a =>
a.AdvocateId == vendorAdvocates.AdvocateId)).ToList();
这是最好的方法吗?似乎错了,比如可能有更简化的方法来使用'contains'关键字或看起来更具可读性的东西......得到所有供应商的拥护者
感谢
答案 0 :(得分:2)
在Advocate_Vendors和Advocates之间使用join
将是正确的方法。
var list = (from vendorAdvocates in db.Advocate_Vendors
join advocates in db.Advocates
on vendorAdvocates.AdvocateId equals advocates.AdvocateId
where vendorAdvocates.VendorId == vendorId
select advocates).ToList();
答案 1 :(得分:1)
var list = (from vendorAdvocates in db.Advocate_Vendors
from advocate in db.Advocates
where vendorAdvocates.VendorId == vendorId &&
vendorAdvocates.AdvocateId = advocate.Id
select advocate)
.ToList();
答案 2 :(得分:0)
如果你正确设置外键和导航属性,应该可以这样写,或类似的东西:
var list = (from vendorAdvocates in db.Advocate_Vendors
where vendorAdvocates.VendorId == vendorId
select db.Advocate).ToList();