我的项目中有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; }
}
每个类中还有许多其他属性.数据库遵循相同的结构.现在我想将分配从数据库映射到视图模型.
我使用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_subject是db_element中的外键,类似地db_element是db_assignment中的外键.在视图模型中,列的名称在某些情况下是不同的.
最佳答案 试试这个,
我假设您的数据库类如下所示.
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);
对我来说很好.