【问题标题】:Automapper related entitiesAutomapper 相关实体
【发布时间】:2019-06-29 12:12:04
【问题描述】:

我的Quotation 模型包含Customer 类型的属性。当我使用以下代码从上下文中获取引用时,我想使用 automapper 填充 Customer 属性:

var quotation = context.Quotation.Include("Customer").Single(q => q.Id == 1);
var quotationDetailsViewModel = mapper.Map<QuotationDetailsViewModel>(quotation);

目前,我的quotation.Customer 已填充,但未映射到quotationDetailsViewModel 中的相应字段。我知道我必须提供一些映射,但不明白在哪里以及如何做。

这是我的模型和视图模型类:

public class Quotation
{
    public long Id {get; set;}
    public long CustomerId {get; set;}
    public Customer Customer {get; set;}
    public string Status {get; set;}
}

public class Customer
{
    public long Id {get; set;}
    public string Name {get; set;}
    public string Address {get; set;}
}

public class QuotationDetailsViewModel
{
    public long QuotationId {get; set;}
    public long CustomerId {get; set;}
    public string Status {get; set;} //This is quotation status
    public string Name {get; set;} //This is customer name
}

这是我的自动映射器 MappingProfile.cs

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<QuotationDetailsViewModel, Quotation>().ReverseMap();
        CreateMap<QuotationDetailsViewModel, Customer>().ReverseMap();
    }
}

我正在使用 .net mvc core 2.2 和 AutoMapper.Extensions.Microsoft.DependencyInjection 版本 6.1.1

【问题讨论】:

    标签: c# asp.net-mvc asp.net-core automapper


    【解决方案1】:

    我正在使用这段代码来映射关系实体

    public class Comment
    {
        public int Id { get; set; }
        public Guid UniqeId { get; set; }
        public string Content { get; set; }
        public virtual Post Post { get; set; } // relational entity
        public CommentStatus CommentStatus { get; set; }
    }
    
    
    public class CommentDto
    {
        public int Id { get; set; }
        public Guid UniqeId { get; set; }
        public string Content { get; set; }
        public Post Post { get; set; }
        public CommentStatus CommentStatus { get; set; }
        public DateTime DateCreated { get; set; }
    }
    

    然后在我的个人资料中

    public class CommentProfile : Profile
    {
        public CommentProfile()
        {
            CreateMap<Comment, CommentDto>(MemberList.None).ReverseMap();
        }
    }
    

    【讨论】:

    • 您的关联实体是哪个?就像我在Quotation 里面有Customer。对不起,我不明白你的例子,请你详细说明。我尝试在我的MappingProfile 中添加MemberList.None,但它没有帮助。
    • 我的相关实体是 Post。所以你需要将相关实体添加到你的 DTO 对象中
    • 好的,但是在我的QuotationDetailsViewModel 中,我已经扁平化了Customer 的属性,以避免出现我认​​为不需要的不必要的属性。所以我想我不能接受你的方法。
    猜你喜欢
    • 2021-01-02
    • 1970-01-01
    • 2016-04-17
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    相关资源
    最近更新 更多