我正在开发一个使用Linq To Sql的WP7应用程序。我使用过Linq,但这是我第一次使用Linq to Sql。我在过滤EntitySet中的数据时遇到了问题。我可能做错了,我不知道。我现在所拥有的可以工作,但我需要得到一个EntitySets过滤。
我有4张桌子。父项、子项、孙项和ParentChild链接表。当我查询ParentChild时,我得到了ParentChild实体,我可以很好地遍历父实体、子实体和孙实体。我想要做的是过滤掉孙子实体。
假设我在父表中有一个父亲和一个母亲。然后我有一个儿子和一个女儿在孩子表中。然后孙子和孙女在孙子餐桌上。当然也有正常的联想,等等。
我想要返回父亲,这也会让我获得所有相关的表。我遇到的问题是对孙子的过滤。假设我只想要孙子,并且有一个性爱的领域。我该怎么做呢?我就是想不通。
下面是我正在使用的代码,它工作得很好,但它拉出了所有的孙子。
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);
}我得到了父母,但我只得到了有女孙子的孩子。我想要父母,所有的孩子(即使他们没有女孙子或没有任何孙子),只有女孙子。
发布于 2012-02-18 03:42:59
经过多次试错和搜寻,我找到了答案。我必须使用AssociateWith选项。
DataLoadOptions dataLoadOptions = new DataLoadOptions();
dataLoadOptions.AssociateWith<Child>(c => c.Grandchild.Where(p => p.Sex == "F"));
this.DataContext.LoadOptions = dataLoadOptions;发布于 2012-02-17 08:14:57
只要在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;我对您的数据模型中的名称做了一些假设,但是您已经明白了。:-)
https://stackoverflow.com/questions/9320962
复制相似问题