代码:
Domain ob = new Domain();
[HttpPost]
public ActionResult Create(Domain ob)
{
try
{
//// TODO: Add insert logic here
FirstTestDataContext db = new FirstTestDataContext();
tblSample ord = new tblSample();
ord = ob;
db.tblSamples.InsertOnSubmit(ord);
db.SubmitChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
我在这里收到错误
无法将类型'mvcInsertLinqForms.Models.Domain'隐式转换为'mvcInsertLinqForms.tblSample'
答案 0 :(得分:1)
您无法将ord
分配给ob
,因为它们的类型不同。您似乎正在尝试将视图模型(ob
)映射到您的域模型(tblSample
)。您可以通过设置域模型的相应属性来执行此操作:
[HttpPost]
public ActionResult Create(Domain ob)
{
try
{
tblSample ord = new tblSample();
// now map the domain model properties from the
// view model properties which is passed as action
// argument:
ord.Prop1 = ob.Prop1;
ord.Prop2 = ob.Prop2;
...
FirstTestDataContext db = new FirstTestDataContext();
db.tblSamples.InsertOnSubmit(ord);
db.SubmitChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
要避免手动执行此映射,您可以使用AutoMapper等工具来帮助您在视图模型和域模型之间来回映射。
答案 1 :(得分:0)
[HttpPost]
public ActionResult (Domain model) // or (FormCollection form), use form.get("phone")
{
//---
return View();
}