我有2张桌子:POHeader和PODetail。我想返回所有具有关联PODetail.ItemId = intItemId的POHeader。我怎么能在LINQ中做到这一点?
这就是我尝试过的。
首先,我的Repository中有一个方法,它使用Include参数来包含PODetails:
public IQueryable<POHeader> SearchForWithDetails(int intFacilityId)
{
return DbSet.Include("PODetails").Where(x => x.FacilityId == intFacilityId);
}
然后将结果传递给:
public IQueryable<POHeader> SearchForPODetailsByItemId(IQueryable<POHeader> poHeaders, int intItemId)
{
//This returns a type of PODetail not POHeader
var q = poHeaders.SelectMany(c => c.PODetails).Where(c => c.ItemId == intItemId);
//In this case, I can't figure out the syntax :(
var p = from poHeader in poHeaders
let filteredPOs = from poDetail in poHeader.PODetails
where poDetail.ItemId == intItemId
select ????
return p;
}
这样做的正确方法是什么?
另外,我可以预见到需要2个结果:
答案 0 :(得分:3)
试试这个;
var result = poHeaders.Where(e => e.PODetails.Any(a => a.ItemId == intItemId));
答案 1 :(得分:1)
假设你的Header-&gt; Detail是一对多的关系,而Detail有一个导航回到它的标题名为.Header:
public IQueryable<POHeader> SearchForPODetailsByItemId(IQueryable<POHeader> poHeaders, int intItemId)
{
var headersForThisItem = poHeaders.SelectMany(pod => pod.PODetails).Where(pod => pod.ItemId == intItemId)
.Select(pod=> pod.Header).Distinct();//.Distinct to eliminate duplicates when 2 Details have the same header. Not necessary if ItemId filter naturally provides distinct results.
return headersForThisItem ;
}
未经测试,但我认为这会给你你想要的东西。