我有一个具有以下内容的实体框架模型:
class Farm{
string owner;
List<Animal> animals;
DateTime StartDate;
}
class Animal{
string Name;
DateTime DOB;
}
问题:
我想选择开始日期 >= 2013/01/01及其动物的农场集合,但也按 DOB >= 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...
有人愿意解释上述内容是如何工作的吗?
基本上查询是选择父实体和通过所需参数过滤的子实体,并且通过“关系修复”的实体框架知道选定的子实体与选定的父实体相关联,因此它们也被添加到父集合中。我认为这是一种 hacky 解决方案,但它确实有效。
——安德烈·D。