【发布时间】:2013-10-03 05:33:40
【问题描述】:
我有一个具有以下内容的实体框架模型:
class Farm{
string owner;
List<Animal> animals;
DateTime StartDate;
}
class Animal{
string Name;
DateTime DOB;
}
问题:
我想选择一个农场集合,其开始日期 >= 2013/01/01 连同它的动物,但也过滤强> 出生日期 >= 2013/06/01。
我尝试了以下方法:
试试1:
//This still shows all animals from each farm, if there is at least one
//animal with the required DOB
var x = context.Farm.Where(y => y.StartDate >= myDate
&& y.Animal.Any(z => z.DOB >= otherDate)
).Include("Animal");
试试2:
//I subclassed the Farm class because i cant instantiate the class
//from Entity Framework directly, and that should be my return type.
class Temp:Farm{}
var x = context.Farm.Where(y => y.StartDate >= myDate).Include("Animal")
.Select(z => new Temp(){
owner = z.owner,
animals = new TrackableCollection<Animal>(){ z.animals.Where(y => y.DOB >= newDate).SingleOrDefault() });
//Couple of things here:
//1: I instantiated a new TrackableCollection because thats what the collection
//type of Animal is inside Entity Framework.
//2: This still doesnt work for some reason, if i use this approach, the list
//of animals in the farm comes with 0 elements.
试试3:
阅读后:Ef-query-with-conditional-include
var x = (from farm in ctx.Farm
from animal in farm.Animal
where animal.DOB => newDate
select new{farm, animal}).AsEnumerable().Select(x=> x.farm).Distinct().ToList();
//I have no idea how this works, but it does...
有人愿意解释一下上面的工作原理吗?
基本上查询是选择父实体和通过所需参数过滤的子实体,并且实体框架通过“Relationship Fixup”知道选定的子实体与选定的父实体相关联,因此它们被添加到父集合中出色地。我认为这是一个 hacky 解决方案,但它确实有效。
--安德烈·D.
【问题讨论】:
-
动物和农场之间需要建立关系。你有没有在你的例子中显示的?
-
是的,我只是为了简单起见使用了这些类,但在我的实际模型中,这些类之间存在关系。实体模型是从 SQL Server 数据库导入的。
-
我已经修改了我的回答来解释你的问题。
标签: c# linq entity-framework