c# - 获取具有部分加载的集合的 Entity Framework 对象

标签 c# linq entity-framework

我有一个 Entity Framework 模型,具有以下内容:

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... 

有人愿意解释一下上面的工作原理吗?

基本上,查询是选择父实体和按所需参数过滤的子实体,并且 Entity Framework 通过“关系修复”知道所选子实体与所选父实体关联,因此它们被添加到父集合中,如下所示出色地。我认为这是一种黑客解决方案,但它确实有效。

--安德烈·D.

最佳答案

Anyone care to explain how the above works?

将以下内容视为两个单独的查询:

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();

突破:

//Give me all farms
from farm in ctx.Farm

//Give me farms with animals with a DOB greater or equal to newDate
from animal in farm.Animal
where animal.DOB => newDate

//Select both so that neither are discluded from the query during execution
select new{farm, animal})

在执行时,查询将仅包含上述数据,因此结果将包含每个农场中的两个,包括过滤后的动物

Distinct 过滤重复项。

关于c# - 获取具有部分加载的集合的 Entity Framework 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19012116/

相关文章:

c# - 如何在 LINQ 上使用 OR 连接 where 子句?

c# - 具有条件连接和非匿名返回的 LINQ 查询

c# - LINQ 等效于 SQL

C# Winforms DataGridView 排序/过滤像 Ms Excel

c# - Visual Studio 2012 网络共享

c# - W3C (IIS) 日志记录不记录我的 WCF 服务的 ClaimsIdentity 用户名

c# - 如何从 JsonTextReader 中获取详细的位置信息

c# - AddOrUpdate 不修改 child

c# - 有什么方法可以优化这个 LINQ to Entities 查询吗?

c# - MVC 5 EF6 工作单元和存储库模式