在基类中定义的属性中使用ExplicitExpansion
时,AutoMapper不会在EF中投影查询。以下代码显示了模型:
/*********** Source Types ***********/
class EntityBase
{
public Guid? CreatedById { get; set; }
public Guid? ModifiedById { get; set; }
[ForeignKey("CreatedById")]
public User CreatedBy { get; set; }
[ForeignKey("ModifiedById")]
public User ModifiedBy { get; set; }
}
class User
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
}
class Script : EntityBase
{
[Key]
public Guid Id { get; set; }
public string Text { get; set; }
}
/*********** Destination Types ***********/
class EntityBaseModel
{
public Guid? CreatedById { get; set; }
public Guid? ModifiedById { get; set; }
public UserModel CreatedBy { get; set; }
public UserModel ModifiedBy { get; set; }
}
class UserModel
{
public Guid Id { get; set; }
public string Name { get; set; }
}
class ScriptModel : EntityBaseModel
{
public Guid Id { get; set; }
public string Text { get; set; }
public new UserModel ModifiedBy { get; set; } //notice the 'new' here? this will work
}
我正在使用以下映射配置:
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Script, ScriptModel>()
.MaxDepth(1)
.ForMember(d => d.ModifiedBy, o => o.ExplicitExpansion())
.ForMember(d => d.CreatedBy, o => o.ExplicitExpansion());
});
以下测试将失败,但它不应该...它应该获取CreatedBy
属性,因为我已明确说过:
/// <summary>
/// This will fail, but it shouldn't.
/// </summary>
[TestMethod]
public void Should_Map_CreatedBy()
{
using (var context = new MyContext())
{
var model = context.Scripts.Include("CreatedBy").ProjectTo<ScriptModel>(null, "CreatedBy").FirstOrDefault();
Assert.IsNotNull(model);
Assert.IsNotNull(model.CreatedBy);
}
}
我也尝试过这些配置,但它不起作用
Mapper.Initialize(cfg =>
{
cfg.CreateMap<EntityBase, EntityBaseModel>();
cfg.CreateMap<User, UserModel>();
cfg.CreateMap<Script, ScriptModel>()
.MaxDepth(1)
.ForMember(d => d.ModifiedBy, o => o.ExplicitExpansion())
.ForMember(d => d.CreatedBy, o => o.ExplicitExpansion());
});
Mapper.Initialize(cfg =>
{
cfg.CreateMap<EntityBase, EntityBaseModel>();
cfg.CreateMap<User, UserModel>();
cfg.CreateMap<Script, ScriptModel>()
.IncludeBase<EntityBase, EntityBaseModel>()
.MaxDepth(1)
.ForMember(d => d.ModifiedBy, o => o.ExplicitExpansion())
.ForMember(d => d.CreatedBy, o => o.ExplicitExpansion());
});
我的映射配置有问题吗?这是一个自动播放器错误吗?
以下是完整的复制品:https://1drv.ms/u/s!AhH0QYI81F61gtIx0q27BZ05EM-xQA
答案 0 :(得分:0)
cfg.CreateMap<User, UserModel>();
cfg.CreateMap<Script, ScriptModel>()
.ForMember(d => d.ModifiedBy, o => o.ExplicitExpansion())
.ForMember(d => d.CreatedBy, o => o.ExplicitExpansion());
var model = context.Scripts.ProjectTo<ScriptModel>(s=>s.CreatedBy).FirstOrDefault()
这对我来说最新版本。