How do I filter related Child Record

2019-05-23 10:03发布

I am using RIA services. I need to select a parent entity (UnitOccupier) which has a number of related child entities(UnitOccupierDetails). I need to filter the child entities to return a single record. How do I do this?

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

Thanks

1条回答
够拽才男人
2楼-- · 2019-05-23 10:39

You cannot include a filtered child collection of the selected parent. You can only include either the full collection or no child collection at all. But as a workaround you could use an intermediate anonymous type, like so:

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
}

Edit

If you want to query for the childs and include their parents (related to question in comment) you could use:

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

I am assuming here that your UnitOccupierDetails class has a navigation property to the parent UnitOccupier.

查看更多
登录 后发表回答