Csharp/C#教程:具有entity framework和编辑多个对象的MVC 3导致“参照完整性约束违反”分享


具有entity framework和编辑多个对象的MVC 3导致“参照完整性约束违反”

我有一个MVC 3项目,我正在使用Entity Framework作为我的模型。 我有一个对象“雇主”,其中包含“地址”和“邮政地址”,我想同时显示(查看)和更新(编辑)(即在页面上显示雇主详细信息和地址详细信息同时更新) )

我的观点似乎很好:

var employer = (from e in entities.Employers.Include("Address").Include("PostalAddress") where e.EmployerNumber == employerNumber select e).First(); return View(employer); 

我的编辑显示正常(即所有文本框都填充了雇主和地址详细信息)

 [HttpPost] public ActionResult Edit(Employer employer) { if (ModelState.IsValid) { entities.Employers.Attach(employer); entities.ObjectStateManager.ChangeObjectState(employer, EntityState.Modified); entities.SaveChanges(); return RedirectToAction("Index"); } return View(employer); } 

但是当我去保存时,我在entities.Employers.Attach(雇主)行上得到以下exception:

发生了引用完整性约束违规:定义引用约束的属性值在关系中的主体和从属对象之间不一致。

当我查看它试图附加的雇主对象时,似乎已经“丢失”了它的Address和PostalAddress项目。

这是我的第一个MVC 3项目,所以任何帮助将不胜感激。

编辑页面视图如下所示

 @model MyProject.BusinessObjects.Employer @{ ViewBag.Title = "Edit Employer Details"; } 

Edit Employer Details

@using (Html.BeginForm()) { @Html.ValidationSummary(true)
Employer
Name
@Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)
Address
Line One
@Html.EditorFor(model => model.Address.LineOne) @Html.ValidationMessageFor(model => model.Address.LineOne)
Line Two
@Html.EditorFor(model => model.Address.LineTwo) @Html.ValidationMessageFor(model => model.Address.LineTwo)
Suburb
@Html.EditorFor(model => model.Address.Suburb) @Html.ValidationMessageFor(model => model.Address.Suburb)
State
@Html.EditorFor(model => model.Address.State) @Html.ValidationMessageFor(model => model.Address.State)
Post Code
@Html.EditorFor(model => model.Address.PostCode) @Html.ValidationMessageFor(model => model.Address.PostCode)

}

我认为你在使用ModelBinder时遇到了问题。

它可能不适合你的复杂类型(我猜测地址和邮政地址是雇主的导航属性)。

你可以试试下面的代码。

 [HttpPost] public ActionResult Edit(Employer employer, FormCollection col) { if (ModelState.IsValid) { var emp = employer; //populate emp.Address and emp.PostalAddress with values from col entities.Employers.Attach(emp); entities.ObjectStateManager.ChangeObjectState(emp, EntityState.Modified); entities.SaveChanges(); return RedirectToAction("Index"); } return View(employer); } 

你能发布你的剃刀文件吗? 我猜测模型绑定不能正常工作。 你是如何创建表单的?

我建议你使用’ViewModel’模式来解决这个问题。

创建一个包含向用户显示的属性的类,并在操作中获取此对象并在模型对象上“转换”它。

会是这样的:

想象一下,你有这些课程:

 public class Employee{ public string Name {get; set;} public Address Address {get; set;} } public class Address { public string Street {get; set;} } 

比你的viewmodel会:

 public class EmployeeViewModel{ public string Name {get; set;} public string Street {get; set;} } 

您可以使用Automapper轻松地在这些对象之间进行转换。

上述就是C#学习教程:具有entity framework和编辑多个对象的MVC 3导致“参照完整性约束违反”分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/990130.html

(0)
上一篇 2021年12月24日
下一篇 2021年12月24日

精彩推荐