c# - Automapper 相关实体
问题描述
我的Quotation
模型包含 type 的属性Customer
。Customer
当我使用以下代码从上下文中获取引用时,我想使用 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.DependencyInjection
6.1.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();
}
}
推荐阅读
- java - 将二叉搜索树节点存储到图顶点的最佳方法
- pandas - 目标 40 超出 nn.CrossEntropyLoss() 的范围
- python - Python类的init函数将自己类的实例作为默认参数
- javascript - ramda/函数式编程 - 基于条件的不同逻辑
- html - 如何摆脱 HTML 中的空白区域
- javascript - 将 Google 日历议程视图制作成卡片
- c - 我应该如何在 C 中实现点和向量?
- javascript - 如果测验在时间结束之前结束,我如何停止计时器功能?Javascript
- ubuntu-18.04 - sqoop 在我的 ubuntu 18.04 和 hadoop 3.1.3 上不起作用
- javascript - 使用 Ajax 创建博客罐后,我无法进行任何其他 Ajax 调用,并且 JsonResponse 返回空字符串