gpt4 book ai didi

asp.net-mvc - 使用 Automapper 映射嵌套类

转载 作者:行者123 更新时间:2023-12-03 20:23:17 25 4
gpt4 key购买 nike

我的项目中有 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从数据库到 View 模型。

我使用 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 中的外键.在某些情况下, View 模型中的列名称是不同的。

最佳答案

尝试这个,

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

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);

对我来说很好用。

关于asp.net-mvc - 使用 Automapper 映射嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35403190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com