1

我有一個現有的數據庫,我已經使用VS2013和EF6構建了一個shell web-app,但我遇到了一些問題。ASP MVC 5 EF 6 - 插入多個表

我的數據庫具有以下表,例如:

Table: Customer (Id, First, Last, Date) 
Table: Assets (Id, CustID) 
Table: Orders (Id, AssetId, CustID) 

當EF創建外殼的webapp,我(其中有真棒)它給了我下面的方法,例如,創建一個新的客戶:

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult Create([Bind(Include="Id, First, Last, Date")] Customer customer) 
.... 
return View(customer) 

在我的數據庫中,我有一個一個客戶向許多訂單和資產,但我不知道如何創建操作過程中使用了這種關係,或任何其他。

我的問題 - 如何「創建」一個新的客戶當這個操作需要跨越多個表?例如,填寫「創建客戶」表單時,您需要添加一個或多個資產和/或訂單

我應該使用存儲過程在三個不同的表中執行多次插入嗎?或者我可以對數據庫進行更改,讓我可以使用所有EF魔術?

感謝您的幫助!

+0

我想我在這裏實際問的是如何在單個表單中使用多個類提交? – syllogistic

+0

聽起來像你的控制器正在使用域模型,而不是使用視圖模型(然後將視圖模型映射到Post動作中的域模型)。 –

回答

2

您可以使用包含所有三個類的視圖模型。

public class CreateCustomerViewModel 
{ 
    public Customer Customer { get; set; } 
    public ICollection<Asset> Assets { get; set; } 
    public ICollection<Order> Orders { get; set; } 
} 

[HttpGet]操作方法將通過這個視圖模型作爲模型,而不是Customer

[HttpGet] 
public ActionResult Create() 
{ 
    CreateCustomerViewModel model = new CreateCustomerViewModel(); 
    return View(model); 
} 

[HttpPost]操作方法將採取CreateCustomerViewModel作爲參數:

[HttpPost] 
public ActionResult Create(CreateCustomerViewModel model) 
{ 
    // Create the Customer with the necessary Assets and Orders and save 
} 

如果你是類和關係被正確配置,加入適當的資產和訂單的導航屬性上的Customer當您插入Customer時,實體應觸發EF自動將資產和訂單插入適當的表中。

+0

非常有幫助,謝謝! – syllogistic