【发布时间】:2015-10-29 10:20:06
【问题描述】:
我正在使用 AutoMapper 将许多实体模型映射到我在控制器和视图中使用的视图模型 (.Net MVC) DB中有很多关系,所以我们的VM有很多孩子(他们有孩子,等等)
public class InvoiceVMFull : VMBase
{
public int Id { get; set; }
public InvoiceType InvoiceType { get; set; }
public string Reference { get; set; }
//.... shortened code for readability
// list all entity fields
public List<string> InvoiceMainAddress { get; set; }
public List<string> InvoiceDlvAddress { get; set; }
}
它工作得很好,但是很慢并且总是从数据库中加载所有关系,而我通常只需要一些数据......
因此,我创建了一些轻型 VM,我想将其用于我们的大部分页面。
public class InvoiceVMLite : VMBase
{
public int Id { get; set; }
public string Reference { get; set; }
//.... shortened code for readability
// list only some of the entity fields (most used)
public StoredFileVM InvoiceFile { get; set; }
}
问题是我找不到方法:
- 将一个实体对象映射到两个虚拟机,以及如何使用上下文(调用的页面或事件)选择正确的实体对象(从数据库加载)
- 将两个 VM 映射到一个实体并仅保存(在 DB 上)使用的 VM 中存在的字段,而不删除不存在的字段
我尝试创建两个 VM 的映射:
Mapper.CreateMap<Invoice, InvoiceVMLite>();
Mapper.CreateMap<Invoice, InvoiceVMFull>();
但是当我尝试调用 Lite 的映射时,它不存在(已被 Full 覆盖):
Mapper.Map(invoice, InvoiceEntity, InvoiceVMLite)
【问题讨论】:
标签: c# asp.net-mvc entity-framework automapper viewmodel