使用Automapper映射嵌套类

时间:2016-02-15 06:56:29

标签: asp.net-mvc asp.net-mvc-5 automapper

我的项目中有3个嵌套级别。像这样:

    public class Assignment
    {
        public Element Element { get; set; }
    }

    public class Element
    {
        public Subject Subject { get; set; }
    }

    public class Subject
    {
        public int? Id { get; set; }

        public string Subject_Title { get; set; }
    }

每个班级都有许多其他属性。数据库遵循相同的结构。现在我想将assignment从数据库映射到视图模型。

我使用automapper编写的映射是第一次工作,但之后却没有。因此Subject的值在后续运行中为null,而Element的值在所有运行中都很好。问题仅限于主题。

有人能指出我正确的方向并告诉我我做错了什么吗?

        Mapper.CreateMap<db_Subject, Subject>();

        Mapper.CreateMap<db_element, Element>()
              .ForMember(dest => dest.Subject, opt => opt.MapFrom(src => src.db_Subject));

        Mapper.CreateMap<db_assignment, Assignment>()
              .ForMember(dest => dest.Element, opt => opt.MapFrom(src => src.db_element));

基本上,db_subjectdb_element中的外键,同样db_elementdb_assignment中的外键。在视图模型中,列的名称在某些情况下是不同的。

1 个答案:

答案 0 :(得分:1)

试试这个,

我假设您的数据库类如下所示。

public class DB_Assignment
{
    public DB_Element Db_Element { get; set; }
}

public class DB_Element
{
    public DB_Subject Db_Subject { get; set; }
}

public class DB_Subject
{
    public int? Db_Id { get; set; }
    public string Db_Subject_Title { get; set; }
}

然后创建一个这样的映射

Mapper.CreateMap<DB_Subject, Subject>()
    .ForMember(destination => destination.Id, options => options.MapFrom(source => source.Db_Id))
    .ForMember(destination => destination.Subject_Title, options => options.MapFrom(source => source.Db_Subject_Title))
    .ReverseMap();

Mapper.CreateMap<DB_Element, Element>()
    .ForMember(destination => destination.Subject, options => options.MapFrom(source => source.Db_Subject))
    .ReverseMap();

Mapper.CreateMap<DB_Assignment, Assignment>()
    .ForMember(destination => destination.Element, options => options.MapFrom(source => source.Db_Element))
    .ReverseMap();

使用如下

var db_Assignment_1 = new DB_Assignment { Db_Element = new DB_Element { Db_Subject = null } };
var assignment_1 = MappingEngine.Map<DB_Assignment, Assignment>(db_Assignment_1);

var db_Assignment_2 = new DB_Assignment { Db_Element = new DB_Element { Db_Subject = new DB_Subject { Db_Id = 1, Db_Subject_Title = "Some title" } } };
var assignment_2 = MappingEngine.Map<DB_Assignment, Assignment>(db_Assignment_2);

var db_Assignment_Lst = new List<DB_Assignment> { db_Assignment_1, db_Assignment_2 };
var assignment_Lst = MappingEngine.Map<List<DB_Assignment>, List<Assignment>>(db_Assignment_Lst);

对我来说很好。