你想要一個視圖模型來保存你想要插入的所有數據,然後在你的控制器中創建基於該視圖模型的對象並使用EF插入。喜歡的東西:
public class MyViewModel
{
public string Name {get; set;}
public string Birthday {get; set;}
public string VerNumber { get; set;}
public string Email {get; set;}
public string Address {get; set;}
// etc etc for the rest of your data
}
然後在你的控制器,使用您的視圖模型來填充你的實體,然後插入使用EF:
[HttpPost]
public ActionResult Add(MyViewModel model)
{
var client = new Client{
Name = model.Name,
Birthday = model.Birthday
};
var clientDetails = new ClientDetails();
//etc for your other entities
using (var context = new MyDbContext)
{
context.Clients.Add(client);
clientDetails.ClientId = client.Id;
context.ClientDetails.Add(clientDetails);
//etc add your other classes
context.SaveChanges();
}
//whatever you want to do here for the result, maybe direct to new controller
//or return view
return View();
}
你可能想看看的整理使用Repository Pattern實體框架代碼並且您還可以查看automapper以從您的視圖模型映射實體,以節省手動操作。
非常感謝您的詳細解答。如果MyViewModel增長,這是正常的。 1)姓名2)姓氏3)生日... 50)沒有。或者除了創建視圖模型之外還有其他解決方案在此先感謝 – DSI
如果您希望用戶輸入/編輯來自不同表格的數據,那麼您肯定需要一個視圖模型,由於過度定位攻擊,還有使用視圖模型而不是實體的安全優勢。 – LightningShield
你好,從多表顯示數據呢? – DSI