如何过滤相关的子记录

时间:2011-04-14 15:11:59

标签: entity-framework linq-to-entities ria

我正在使用RIA服务。我需要选择一个父实体(UnitOccupier),它有许多相关的子实体(UnitOccupierDetails)。我需要过滤子实体以返回单个记录。我该怎么做?

var q = from uo in _unitOccupierContext.GetUnitOccupierQuery()
        where uo.UnitOccupierDetails.????
                                     ---> I cant get to the child properties here

由于

1 个答案:

答案 0 :(得分:3)

您不能包含所选父级的已过滤子级集合。您只能包含完整集合或根本不包含子集合。但作为一种解决方法,您可以使用中间匿名类型,如下所示:

var q = (from uo in _unitOccupierContext.GetUnitOccupierQuery() 
         select new {
             Parent = uo,
             Childs = uo.UnitOccupierDetails
                        .Where(uod => uod.MyDetailsProp == MyDetailsValue)
         }).FirstOrDefault();

if (q != null)
{
    UnitOccupier selectedUnitOccupier = q.Parent;
    selectedUnitOccupier.UnitOccupierDetails = q.Childs.ToList();
    // selectedUnitOccupier now only contains the filtered childs
}

修改

如果您想查询孩子并包含他们的父母(与评论中的问题相关),您可以使用:

var q = _unitOccupierContext.GetUnitOccupierQuery()
         .SelectMany(uo => uo.UnitOccupierDetails
                             .Where(uod => uod.MyDetailsProp == MyDetailsValue))
         .Include(uod => uod.UnitOccupier)
         .FirstOrDefault(); // or .ToList() if you expect more than one record
// q is now null or a single UnitOccupierDetails entity
// with a reference to its parent

我假设您的UnitOccupierDetails类具有父UnitOccupier的导航属性。