首页 > 解决方案 > Automapper 相关实体

问题描述

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

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

目前, myquotation.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.DependencyInjection6.1.1 版本

标签: c#asp.net-mvcasp.net-coreautomapper

解决方案


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

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

推荐阅读