简体   繁体   English

实体框架核心不包含 ToListAsync 时,但包含 FirstOrDefaultAsync

[英]Entity framework core does not include when ToListAsync, but does with FirstOrDefaultAsync

I have a query that looks like this (Entity framework core 2.2.7):我有一个看起来像这样的查询(实体框架核心 2.2.7):

        var query = from row in _entities.MyEntities
                .Include(e => e.MyEntityChildren)
                .Include(e => e.MyParent)
                .Include(e => e.MyParent2)
                .Include(e => e.MyParent3)
                .Include(e => e.MyParent4)
            where row.MyParent4.Id == "whatever" &&
                  dict.Contains(row.Id) &&
                  active.Contains(row.Status)
            select row;

Then I have different results based on how I execute the query:然后根据我执行查询的方式得到不同的结果:

var e = await query.FirstOrDefaultAsync();

Works correct工作正常

var e = await query.Distinct().ToListAsync();

Does not populate MyParent3.不填充 MyParent3。 But both queries include all the other relations.但是这两个查询都包括所有其他关系。

So my question is.所以我的问题是。 Is this a known issue?这是一个已知的问题? What is the difference between first and list? first 和 list 和有什么不一样? And does anything know how to resolve it?有什么知道如何解决的吗?

The generated sql looks the same and MyParent3 is fetched from database in both cases so I suspect it is something with the serializer.生成的 sql 看起来相同,并且 MyParent3 在两种情况下都是从数据库中获取的,所以我怀疑它与序列化程序有关。 This worked in entity framework core 2.0.9这在实体框架核心 2.0.9 中有效

EDIT:forgot distinct!编辑:忘记了!

Difference between first and list assuming data of (2, 3, 4, 1) from your query:假设查询中的 (2, 3, 4, 1) 数据,第一个和列表之间的区别:
- Lists is similar to an array, which contains more than 1 element will get ([2, 3, 4, 1]) - Lists 类似于一个数组,其中包含超过 1 个元素会得到 ([2, 3, 4, 1])
- First only contains 1 element, which is the first element (2) - First 仅包含 1 个元素,即第一个元素 (2)

As to why it is not working, my best guess is:至于为什么它不起作用,我最好的猜测是:
1. The format of the data obtained through your query is not able to serialize into a list, therefore there is no output there. 1、你查询得到的数据格式不能序列化成列表,所以没有output。
2. Your first example does not have the actual data too, which will return a default item 2.您的第一个示例也没有实际数据,这将返回一个默认项

I have no idea why it happens and also don't really want to post the whole project because MyEntity is eg Orders and MyParent3 is ShippingInformation我不知道为什么会发生,也不想发布整个项目,因为 MyEntity 是例如 Orders 而 MyParent3 是 ShippingInformation

But, if I loop the result like this it works:但是,如果我像这样循环结果,它可以工作:

var result = new List<MyDomainEntity>();
foreach (var dto in query.Distinct())
{
    result.Add(GetEntity(dto));
}

I will just leave the result if anyone else experience this.如果其他人遇到这种情况,我会留下结果。

EDIT: I had made a naming conflict.编辑:我发生了命名冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM