[英]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; }
}
那么您有幾種選擇:
PhoneNumberVM
實例映射到一個PhoneNumber
實例,或者 Mapper.CreateMap<PhoneNumberVM, PhoneNumber>()
,只需調用Mapper.Map<PersonVM, Person>(model)
即可將模型映射到您的實體。 當然,您必須確保正確構造模型,但是只要您使用相同的模型來生成HTML表單,這並不是很難。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.