繁体   English   中英

AutoMapper和创建时一对多映射

[英]AutoMapper and mapping one-to-many on Create

因此,我的数据库在客户和订单之间具有一对多关联。
映射数据以显示客户及其订单没有问题。 但是在创建客户时是否有办法映射这些内容?

例如:“仅用于测试映射的非常基本的viewModel”

public class CVM  
{  
    public string ContactName { get; set; }  //Part of the Customer Table  
    public DateTime OrderDate { get; set; }  //Part of the Orders Table and 
    //would have to be passed into the Orders List of the EF-Customer-Object  
}

因此,创建视图仅具有“名称”和“日期”两个输入。 “仅用于测试映射的非常基本的控制器;)”

[HttpPost]  
public ActionResult Create(CVM model)  
{  
    Mapper.CreateMap<CVM, Customer>();  
    Customer customer = Mapper.Map<CVM, Customer>(model);  
    return View();  
}

因此,ContactName被正确映射。 问题是OrderDate。 AutoMapper必须创建一个Order实例,设置OrderDate的值,并将其传递给Customer对象的OrdersCollection。 AutoMapper能够做到这一点还是我完全错了?

希望您理解我的解释,并且有人可以回答我。

谢谢大家

我认为您是错误的做法。 您应该做的是实例化一个Customer实例,然后使用AutoMapper映射其属性。

因此,您的代码如下所示:

[HttpPost]  
public ActionResult Create(CVM model)  
{  
    Mapper.CreateMap<CVM, Customer>();
    Customer customer = /* Construct or get a Customer instance, eg from DB. */
    Mapper.Map<CVM, Customer>(model, customer);  
    return View();  
}

顺便说一句,您应该确保仅在应用程序启动期间才具有Mapper.CreateMap<CVM, Customer>()指令,否则,您将不必要地对每个请求执行此步骤(可能成本Mapper.CreateMap<CVM, Customer>() )。

编辑

看来我看错了原始问题。 如果目的是创建具有关联对象的Customer,则Automapper可以通过几种不同的方式为您提供帮助(我将继续使用您在注释中提供的Person / PhoneNumber示例)。

鉴于您的实体和视图模型为:

public Person {
  public string Name { get; set; }
  public string List<PhoneNumber> Numbers { get; set; }
}

public PersonVM {
  public string Name { get; set; }
  public string IList<PhoneNumberVM> Numbers { get; set; }
}

public PhoneNumber {
  public int Type { get; set; }
  public string Number { get; set; }
}

public PhoneNumberVM {
  public int Type { get; set; }
  public string Number { get; set; }
}

那么您有几种选择:

  1. 您可以尝试编写自定义映射规则,以便将每个PhoneNumberVM实例映射到一个PhoneNumber实例,或者
  2. 您可以添加一个Mapper.CreateMap<PhoneNumberVM, PhoneNumber>() ,只需调用Mapper.Map<PersonVM, Person>(model)即可将模型映射到您的实体。

当然,您必须确保正确构造模型,但是只要您使用相同的模型来生成HTML表单,这并不是很难。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM