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。
内部例外是:
违反PRIMARY KEY约束'PK_dbo.AppleOranges'。无法在对象'dbo.AppleOranges'中插入重复键。重复键值为(1,3)。\ r \ n语句已终止。
有什么想法吗?
AppleController:
//
// 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);
}
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>
}
答案 0 :(得分:8)
在向其添加项目之前,您必须先加载Apple.Oranges
。如果加载了集合,EF的更改跟踪器将知道哪些关联是新的,哪些已经存在,并且只保存新的关联。
您可以通过
加载该集合db.Entry(Apple).Collection(a => a.Oranges).Load()
您可以删除代码
if (Apple.Oranges == null)
Apple.Oranges = new List<Orange>();