我在StackOverflow上花了一个下午,Google正在寻找一种使用linq to entity进行简单SQL查询的方法。我试图通过多对多关系从两个表中获取数据。在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.Vendors是一个集合而无效,我想要的只是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();
编辑/更新 在ElMent向我提供正确答案之后,我想出了如何使用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();
答案 0 :(得分:0)
这个怎么样?请参阅第二行中的“from v in t.Vendors”。
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();
Mor信息在这里: https://msdn.microsoft.com/en-us/library/bb386932(v=vs.110).aspx