我花了一个下午的StackOverflow和谷歌寻找一种方法来做一个简单的SQL查询使用linq到实体。我试图从两个表通过多对多关系连接的数据。在SQL中,我将这样写查询:
SELECT v.[VendorID]
, t.[UnitNumber]
, t.[Name]
, t.[Address]
, t.[CityStateZip]
FROM [Tenant] t
INNER JOIN [TenantVendor] tv ON tv.[TenantID] = t.[TenantID]
INNER JOIN [Vendor] v on v.[VendorID] = tv.[VendorID]
WHERE t.[UnitNumber] LIKE '%100A%'
AND t.[CompanyID] = 17874;
我在列表中有一个对象,我选择了它的数据它看起来像这样它直接应用于网格:
public class SearchObject
{
public int IDField { get; set; }
public string UniqueField { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string CityStateZip { get; set; }
}
问题在于,m2m表仅由两个表中的主键组成,因此它没有实体可选择。它们在彼此的实体下显示为如下的集合(来自租户实体):
public virtual ICollection<Vendor> Vendors { get; set; }
我更喜欢lambda表达式,但查询也会工作得很好。我得到的最接近的是这两个:
SearchData = DBContext.Tenants
.Where(t => t.Company.Name == CompanyName && t.UnitNumber.ToString().Contains(SearchText))
.OrderBy(DynamicSort)
.Skip(StartRow)
.Take(PageSize)
.Select(t => new SearchObject { IDField = t.Vendors, UniqueField = t.UnitNumber.ToString(), Name = t.Name, Address = t.Address, CityStateZip = t.CityStateZip })
.ToList();
这个不行,因为t. vendor是一个集合,我想要的只是vendorID。
这一个工作,但返回太多的记录,因为它缺少两个表之间的连接:
SearchData = (from t in DBContext.Tenants
from v in DBContext.Vendors
where t.Company.Name == CompanyName && t.UnitNumber.ToString().Contains(SearchText)
select new SearchObject { IDField = v.VendorID , UniqueField = t.UnitNumber.ToString(), Name = t.Name, Address = t.Address, CityStateZip = t.CityStateZip })
.ToList();
EDIT/UPDATE在element为我提供了正确的答案后,我想出了如何使用c#方法实现相同的结果,SelectMany是关键。
SearchData = DBContext.Tenants
.Where(t => t.Company.Name == CompanyName && t.UnitNumber.ToString().Contains(SearchText))
.OrderBy(DynamicSort)
.Skip(StartRow)
.Take(PageSize)
.SelectMany(t=>t.Vendors.Select(v => new SearchObject { IDField = v.VendorID, UniqueField = t.UnitNumber.ToString() + " - " + v.VendorNumber, Name = t.Name, Address = t.Address, CityStateZip = t.CityStateZip }))
.ToList();
这个怎么样?见第二行"from v in t.v商贩"
SearchData = (from t in DBContext.Tenants
from v in t.Vendors
where t.Company.Name == CompanyName && t.UnitNumber.ToString().Contains(SearchText)
select new SearchObject { IDField = v.VendorID , UniqueField = t.UnitNumber.ToString(), Name = t.Name, Address = t.Address, CityStateZip = t.CityStateZip })
.ToList();
更多信息在这里:https://msdn.microsoft.com/en-us/library/bb386932 (v = vs.110) . aspx