自动映射器相关实体

时间:2019-06-29 12:12:04

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

我有一个Quotation模型,其中包含类型为Customer的属性。当我使用以下代码从上下文中获取引用时,我想使用自动映射器填充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一起使用

1 个答案:

答案 0 :(得分:0)

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

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