【发布时间】:2018-02-18 01:58:25
【问题描述】:
我的设置
- ASP.NET Core 2.0
- EntityFrameworkCore 2.0.1
- AutoMapper 6.2.2
问题
我有一个名为PersonDetail 的DTO 和一个名为Person 的实体的项目。
当我打电话时
db.People.Where(p => p.FirstName == "Joe").Union(db.People.Where(p => Age > 30)).ProjectTo<PersonDetail>(mapperConfig).ToList();
我没有收到 PersonDetail DTO 和 Entity Framework (Core) 抛出异常消息:
ArgumentException:输入序列必须具有“Test.Module.Entities.Person”类型的项目,但它具有“Test.Module.Dtos.PersonDetail”类型的项目。
没有问题的例子
当我运行代码时:
db.People.Where(p => p.FirstName == "Joe").Union(db.People.Where(p => Age > 30)).ToList();
我得到了Person 实体,没有例外。
执行计划
这是一个工作计划(有一个工会):
{value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[Test.Module.Entities.Person]).Where(entity => ((entity != null) And ((63ed0ebd-2c02-4496-ac8d -b836cbf13259 == entity.CreatedBy) 或 (393a6bb0-b437-4664-beb0-6800f509451b == entity.CreatedBy))))).Union(value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[Test.Module.Entities .Person]))}
现在这是相同的计划,但也有自动映射器投影:
{value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[Test.Module.Entities.Person]).Where(entity => ((entity != null) And ((63ed0ebd-2c02-4496-ac8d -b836cbf13259 == entity.CreatedBy) 或 (393a6bb0-b437-4664-beb0-6800f509451b == entity.CreatedBy))))).Union(value(Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[Test.Module.Entities .Person])).Select(dto => new PersonDetail() {FirstName = dto.FirstName, LastName = dto.LastName, Deleted = dto.Deleted, Age = dto.Age, CreatedUtc = dto.CreatedUtc, CreatedBy = dto。 CreatedBy, Id = dto.Id, RecordVersion = dto.RecordVersion, DisplayLabel = ((dto.FirstName + " ") + dto.LastName)})}
注意:
我只是调用 ToList 来将这个问题简化为最小的形式。我知道这似乎不需要在此示例中使用 ProjectTo。在我的实际代码中,我们使用的是 OData,我们需要将最终结果作为 DTO 作为 Queryable 对象的投影查询。我也明白这个 Union 并不是一个很好的联合示例,再次,只是为了简化联合问题。
Ia 还在各自的 GitHub 项目上打开了问题:
EntityFrameworkCore:https://github.com/aspnet/EntityFrameworkCore/issues/11033
AutoMapper:https://github.com/AutoMapper/AutoMapper/issues/2537
【问题讨论】:
-
感谢@LucianBargaoanu!这非常有帮助,并帮助我发现这实际上是工会的一个问题。我没有意识到我的查询被进一步操纵,而联合实际上是计划的一部分。我已更新问题以反映这一点。
标签: c# automapper union projection ef-core-2.0