【问题标题】:Automapper find best mapping [closed]Automapper 找到最佳映射 [关闭]
【发布时间】:2023-03-10 04:01:01
【问题描述】:

我正在使用带有实体框架的 AutoMapper。我有一个实体层次结构:

    • 学生
    • 工人

每个业务对象都有一个到数据库中实体的映射。要将业务对象转换为实体,我使用 AutoMapper v6.2.2 我想知道是否有更好的方法来找到“最佳”映射,或者我真的需要在代码中有这样的东西:

    public PersonEntity MapPerson(Person person)
    {
        switch (person.Type)
        {
            case PersonType.Unknown:
                return Mapper.Map<PersonEntity>(person);
            case PersonType.Student:
                return Mapper.Map<StudentEntity>(person);
            case PersonType.Worker:
                return Mapper.Map<WorkerEntity>(person);

            default:
                throw new ArgumentOutOfRangeException();
        }
    }

好消息是,我已经有一个“类型”枚举用于鉴别器和类似的东西,但它仍然感觉不对。也许你可以帮忙。

【问题讨论】:

    标签: c# entity-framework mapping automapper


    【解决方案1】:

    你可以这样做...

    var mapped = Mapper.Map(person, person.GetType(), typeof(PersonEntity));
    

    有关详细信息,请参阅 AutoMapper 文档。 http://docs.automapper.org/en/stable/Mapping-inheritance.html

    【讨论】:

    • 非常感谢。不知道 automapper 有这么好的文档。
    【解决方案2】:

    AutoMapper 支持mapping inheritance。映射应如下所示:

    class PersonMapperProfile : AutoMapper.Profile
    {
        public PersonMapperProfile()
        {
            this.CreateMap<Student, StudentEntity>();
            this.CreateMap<Worker, WorkerEntity>();
            this.CreateMap<Person, PersonEntity>()
                .Include<Student, StudentEntity>()
                .Include<Worker, WorkerEntity>();
        }
    }
    

    现在,当您将 Person 映射到 PersonEntity 时,AutoMapper 将创建正确的基本类型或子类型。

    【讨论】:

      猜你喜欢
      • 2011-04-11
      • 2019-02-01
      • 2014-03-15
      • 2022-01-04
      • 1970-01-01
      • 2020-06-05
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多