How do I filter related Child Record
I am using RIA services. I need to select a parent entity (UnitOccupier
) which has a number of related child enti开发者_如何学Goties(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
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
.
精彩评论