Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 自动映射-包含忽略相同命名属性的数据库_C#_Automapper - Fatal编程技术网

C# 自动映射-包含忽略相同命名属性的数据库

C# 自动映射-包含忽略相同命名属性的数据库,c#,automapper,C#,Automapper,我正在尝试使用IncludeBase。它似乎在基类上的相同命名属性上存在问题。这些不包括在基本映射中,而是自动解析的。我使用的是automapper 4.2版 与此类似的情况: class Program { static void Main(string[] args) { MapperConfiguration conf = new MapperConfiguration((cfg) => { cfg.Create

我正在尝试使用IncludeBase。它似乎在基类上的相同命名属性上存在问题。这些不包括在基本映射中,而是自动解析的。我使用的是automapper 4.2版

与此类似的情况:

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:是的,他们应该添加一些方法来定义这种行为。”