LinqToSql筛选器实体集
本文关键字:实体 筛选 LinqToSql | 更新日期: 2023-09-27 18:24:50
我正在使用Linq-To-Sql开发一个WP7应用程序。我使用过Linq,但这是我第一次将Linq用于Sql。我在EntitySet中筛选数据时遇到问题。我可能做错了,我不知道。我现在所拥有的是有效的,但我需要过滤其中一个EntitySet。
我有4张桌子。Parent、Child、Grandchild和ParentChild链接表。当我查询ParentChild时,我会返回ParentChild实体,并且我可以很好地遍历Parent、Child和Grandchild实体。我想做的是过滤孙子实体。
比方说,我有一个父亲和母亲在父母的桌子上。然后我有一个儿子和女儿在儿童桌上。然后一个孙子和孙女在孙子桌上。当然也有正常的关联,等等。
我想归还父亲,这也让我所有相关的表格都很好。我的问题是过滤孙子。比方说,我只想要一个孙子,有一块性爱的场地。我该怎么做?我好像就是想不通。
这是我正在使用的代码,它工作得很好,但它吸引了所有的孙子。
IQueryable<ParentChild> parentChild = from ParentChild c in DataContext.ParentChild
where c.ParentId == this.parentId
select c;
foreach (Grandchild grandchild in parentChild.SelectMany(parent => parent.Child.Grandchild))
{
Console.WriteLine(grandchild.Name);
}
所以如果我这样做:
IQueryable<ParentChild> parentChild = from ParentChild c in DataContext.ParentChild
where c.ParentId == this.parentId && c.Child.Grandchild.Any(a => a.Sex == "F")
select c;
foreach (Grandchild grandchild in parentChild.SelectMany(parent => parent.Child.Grandchild))
{
Console.WriteLine(grandchild.Name);
}
我得到了父母,但我只得到了有女孙子的孩子。我想要父母,所有的孩子(即使他们没有女孙子或没有孙子),只有女孙子。
经过反复尝试和搜索,我找到了答案。我必须使用AssociateWith选项。
DataLoadOptions dataLoadOptions = new DataLoadOptions();
dataLoadOptions.AssociateWith<Child>(c => c.Grandchild.Where(p => p.Sex == "F"));
this.DataContext.LoadOptions = dataLoadOptions;
只要您在SQL中正确设置了外键;LINQ to SQL将能够为您提供与外键关系匹配的关联属性。
如果你的外键设置好了,你就可以执行以下操作。。。
var query = from p in DataContext.Parent
//make sure they have at least 1 female grandchild
where p.GrandChilds.Any(gc => gc.IsFemale)
select p;
我对数据模型中的名称做了一些假设,但你明白了。:-)