3

我在 Apple 和 Orange 表之间存在多对多关系。

public class Apple
{
    [Key]
    public int AppleID { get; set; }

    [Required]
    public string AppleName { get; set; }

    [NotMapped]
    public int[] SelectedOranges { get; set; }

    public virtual ICollection<Orange> Oranges { get; set; }

}

public class Orange
{

    [Key]
    public int OrangeID { get; set; }
    public String OrangeName { get; set; }
    public virtual ICollection<Apple> Apples { get; set; }
}

在 Data Context 类中,OnModelCreating 方法被覆盖,如下所示

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        //----------------------------------------------------------------
        //Creating a Association (Intermediate Table) which
        //will hold M2M relations from Student to Course.
        //----------------------------------------------------------------

        modelBuilder.Entity<Apple>()
            .HasMany(c => c.Oranges)
            .WithMany(t => t.Apples);
    }

当我在 ASP.NET MVC 应用程序中保存来自控制器的编辑值时,出现以下异常:

保存不为其关系公开外键属性的实体时发生错误。EntityEntries 属性将返回 null,因为无法将单个实体标识为异常源。通过在实体类型中公开外键属性,可以更轻松地在保存时处理异常。有关详细信息,请参阅 InnerException。

内部异常是:

违反主键约束“PK_dbo.AppleOranges”。无法在对象“dbo.AppleOranges”中插入重复键。重复键值为 (1, 3)。\r\n语句已终止。

任何想法?

苹果控制器:

    //
    // GET: /Apple/Edit/5

    public ActionResult Edit(int id = 0)
    {

        Apple Apple = db.Apples.Find(id);
        if (Apple == null)
        {
            return HttpNotFound();
        }
        var selectedvalues = new List<Orange>();
        Apple.SelectedOranges = new int[Apple.Oranges.Count];
        int j=0;
        foreach (var i in Apple.Oranges)
        {
            selectedvalues.Add(i);
            Apple.SelectedOranges[j++] = db.Oranges.ToList().IndexOf(i)+1;
        }
        ViewBag.OrangesList = new MultiSelectList(db.Oranges, "OrangeID", "OrangeName", selectedvalues);
        return View(Apple);
    }

    //
    // POST: /Apple/Edit/5

    [HttpPost]
    public ActionResult Edit(Apple Apple)
    {
        if (ModelState.IsValid)
        {
            db.Entry(Apple).State = EntityState.Modified;
            foreach (var i in Apple.SelectedOranges)
            {
                if (Apple.Oranges == null)
                    Apple.Oranges = new List<Orange>();
                Apple.Oranges.Add(db.Oranges.Find(i));
            }
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.OrangesList = new MultiSelectList(db.Oranges, "OrangeID", "OrangeName", Apple.SelectedOranges);
        return View(Apple);
    }

苹果编辑视图:

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

<fieldset>
    <legend>Apple</legend>

    @Html.HiddenFor(model => model.AppleID)

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


    <div class="editor-label">
        @Html.LabelFor(model => model.Oranges)
    </div>
    <div class="editor-field">
        @Html.ListBoxFor(m=>m.SelectedOranges,(MultiSelectList)ViewBag.OrangesList)
        @Html.ValidationMessageFor(model => model.Oranges)
    </div>

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

}

4

1 回答 1

8

您必须先加载Apple.Oranges,然后再向其中添加项目。如果加载了集合,EF 的更改跟踪器将知道哪些关联是新的,哪些已经存在,并且只会保存新的关联。

您可以通过以下方式加载集合

db.Entry(Apple).Collection(a => a.Oranges).Load()

你可以删除代码

if (Apple.Oranges == null)
    Apple.Oranges = new List<Orange>();
于 2013-07-10T07:33:07.943 回答