简体   繁体   English

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

[英]MVC 3 with Entity Framework and Editing Multiple Objects leads to “referential integrity constraint violation”

I have an MVC 3 project that I am working on using Entity Framework as my model. 我有一个正在使用Entity Framework作为模型的MVC 3项目。 I have an object "Employer" that has "Address" and "PostalAddress" that I would like to display (view) and update (edit) at the same time (ie on page with employer details and address details being updated at the same time) 我有一个对象“ Employer”,具有“ Address”和“ PostalAddress”,我想同时显示(查看)和更新(编辑)(即页面上的雇主详细信息和地址详细信息同时更新) )

My view seems to work fine: 我的观点似乎很好:

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

My edit shows up fine (ie all of the textboxes are populated with both employer and address details) 我的编辑显示正常(即,所有文本框都填有雇主和地址的详细信息)

[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);
}

But when I go to save I get the following exception on the entities.Employers.Attach(employer) line: 但是当我去保存时,在entities.Employers.Attach(employer)行上得到以下异常:

A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship. 发生参照完整性约束冲突:定义参照约束的属性值在关系中的主体对象和从属对象之间不一致。

When I look at the employer object it is trying to attach it seems to have "lost" it's Address and PostalAddress items. 当我查看雇主对象时,它试图附加,似乎“丢失”了它的Address和PostalAddress项目。

This is my first MVC 3 project so any help would be appreciated. 这是我的第一个MVC 3项目,因此将不胜感激。

The edit page view looks like this 编辑页面视图如下所示

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

<h2>Edit Employer Details</h2>

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <fieldset>

        <legend>Employer</legend>
            <div class="editor-label">Name</div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </div>

            <fieldset>
                <legend>Address</legend>
                    <div class="editor-label">Line One</div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Address.LineOne)
                        @Html.ValidationMessageFor(model => model.Address.LineOne)
                    </div>

                    <div class="editor-label">Line Two</div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Address.LineTwo)
                        @Html.ValidationMessageFor(model => model.Address.LineTwo)
                    </div>

                    <div class="editor-label">Suburb</div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Address.Suburb)
                        @Html.ValidationMessageFor(model => model.Address.Suburb)
                    </div>

                    <div class="editor-label">State</div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Address.State)
                        @Html.ValidationMessageFor(model => model.Address.State)
                    </div>

                    <div class="editor-label">Post Code</div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.Address.PostCode)
                        @Html.ValidationMessageFor(model => model.Address.PostCode)
                    </div>
            </fieldset>

        <p>
            <input type="submit" value="Save Changes" />
        </p>
    </fieldset>
}

Could you please post your razor file? 您能张贴您的剃须刀文件吗? I am guessing that the modelbinding is not working properly. 我猜想modelbinding不能正常工作。 How are you creating the form? 您如何创建表格?

I would suggest you to use the 'ViewModel' pattern to address this issue. 我建议您使用“ ViewModel”模式来解决此问题。

Create a Class that contains the properties that are shown to the user, and in the action, get this object and 'transform' it on the model object. 创建一个包含向用户显示的属性的类,然后在操作中获取此对象并将其“转换”到模型对象上。

Would be something like this: 将是这样的:

Imagine you have these classes: 假设您有以下课程:

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

Than your viewmodel would be: 比您的视图模型将是:

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

You can use Automapper to easily convert between those objects. 您可以使用Automapper在这些对象之间轻松转换。

I think you are having problems with the ModelBinder. 我认为您在使用ModelBinder时遇到问题。

Its probably not working with complex types for you (I'm guessing Address and PostalAddress are navigational properties of Employer). 它可能不适用于您的复杂类型(我猜Address和PostalAddress是Employer的导航属性)。

you could try the code below. 您可以尝试下面的代码。

[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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM