C# 自动映射-包含忽略相同命名属性的数据库
我正在尝试使用IncludeBase。它似乎在基类上的相同命名属性上存在问题。这些不包括在基本映射中,而是自动解析的。我使用的是automapper 4.2版 与此类似的情况:C# 自动映射-包含忽略相同命名属性的数据库,c#,automapper,C#,Automapper,我正在尝试使用IncludeBase。它似乎在基类上的相同命名属性上存在问题。这些不包括在基本映射中,而是自动解析的。我使用的是automapper 4.2版 与此类似的情况: class Program { static void Main(string[] args) { MapperConfiguration conf = new MapperConfiguration((cfg) => { cfg.Create
class Program
{
static void Main(string[] args)
{
MapperConfiguration conf = new MapperConfiguration((cfg) =>
{
cfg.CreateMap<FooBase, FooModelBase>()
.ForMember(e => e.Error, opt => opt.Ignore());
cfg.CreateMap<Foo, FooModel>()
.IncludeBase<FooBase, FooModelBase>();
});
IMapper mapper = conf.CreateMapper();
//works just fine
FooModelBase fooModelBase = mapper.Map<FooModelBase>(new FooBase());
//throws an exception
FooModel fooModel = mapper.Map<FooModel>(new Foo());
}
}
class FooBase
{
public string Error { get; set; }
}
class Foo : FooBase { }
class FooModelBase
{
public string Error
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
}
class FooModel : FooModelBase { }
类程序
{
静态void Main(字符串[]参数)
{
MapperConfiguration conf=新的MapperConfiguration((cfg)=>
{
cfg.CreateMap()
.ForMember(e=>e.Error,opt=>opt.Ignore());
cfg.CreateMap()
.IncludeBase();
});
IMapper mapper=conf.CreateMapper();
//很好用
foododelbase foododelbase=mapper.Map(newfoobase());
//抛出异常
FooModel FooModel=mapper.Map(新的Foo());
}
}
类食品库
{
公共字符串错误{get;set;}
}
类Foo:FooBase{}
类FoodModelBase
{
公共字符串错误
{
获取{抛出新的NotImplementedException();}
设置{抛出新的NotImplementedException();}
}
}
类FooModel:FooModelBase{}
我已经预料到,该应用程序不会抛出异常,但它确实抛出了异常。有什么建议可以解决这个问题吗?这里的关键是AutoMapper如何在继承的映射上优先考虑可能的源
正如您在Automapper GitHub项目中所看到的,当您包括继承的映射时,会引入额外的复杂性,因为有多种方法可以映射属性
这些来源的优先顺序如下:
.MapFrom()
)Ignore()
来解决此问题:
cfg.CreateMap<Foo, FooModel>()
.ForMember(e => e.Error, opt => opt.Ignore())
.IncludeBase<FooBase, FooModelBase>();
cfg.CreateMap()
.ForMember(e=>e.Error,opt=>opt.Ignore())
.IncludeBase();
所以没有其他方法可以做到这一点,要么编写我自己的include基扩展,要么显式添加基类中的每个ignore映射。“这太可悲了。@eCorke:是的,他们应该添加一些方法来定义这种行为。”