【发布时间】:2017-12-29 02:12:11
【问题描述】:
我正在学习 Automapper 和 EF Core,并在尝试对基于导航属性计算的 get-only 属性进行建模时偶然发现了一个问题。 我有两个模型:
public class Parent
{
public int Id {get;set;}
public string Name {get;set;}
public ICollection<Child> Childs {get;set;}
public int WantedChildCount {get{return Childs?.Count(c=>c.Type!=1)??0;}
}
public class Child
{
public int Id {get;set;}
public string Name {get;set;}
public int Type {get;set;}
}
一个 DTO:
public class VM
{
public string Name{get;set;}
public int WantedCount{get;set;}
}
并尝试从 Parent 自动映射 VM,例如:
var c = context.Parents.Include(p => p.Childs).ProjectTo<VM>().FirstOrDefault();
Automapper 配置如下:
Mapper.Initialize(cfg=>
cfg.CreateMap<Parent, VM>()
.ForMember(d=>d.WantedCount, o => o.MapFrom(s=>s.WantedChildCount));
问题在于生成的 VM 字段 WantedCount 未填充。在日志中我发现了消息
The Include operation for navigation: 'p.Childs' was ignored because the target navigation is not reachable in the final query results.
这很简单,所以将这个操作分成两个独立的:首先获取 Parent,然后是 Mapper.Map。 此外,它可以在像这样更改地图时工作:
cfg.CreateMap<Parent, VM>()
.ForMember(d=>d.WantedCount, o => o.MapFrom(s=>s.Childs(c=>c.Type!=1));
但是这样我会完全忽略模型中的 get-only 属性。 我想了解问题是什么,我该如何解决。
或者我什至应该以某种方式将计算转移到数据库端?但我想避免将此属性存储在数据库中。
【问题讨论】:
标签: .net automapper entity-framework-core