在DbContext中保留多个具有相同键的对象
本文关键字:对象 DbContext 保留 | 更新日期: 2023-09-27 18:13:27
我正在尝试创建ASP。NET MVC web应用程序首先使用实体框架代码。我有两个简单的模型
public class Assignment
{
public int Id { get; set; }
[ForeignKey("Initiator")]
public int InititatorId { get; set; }
public virtual User Initiator { get; set; }
public virtual List<User> Debtors { get; set; }
public virtual List<User> Responsibles { get; set; }
public Assignment()
{
Debtors = new List<User>();
Responsibles = new List<User>();
}
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
}
和我的DbContext看起来像
public class AssignmentContext : DbContext
{
public DbSet<Assignment> Assignments { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Assignment>()
.HasRequired(r => r.Initiator)
.WithMany()
.WillCascadeOnDelete(false);
modelBuilder.Entity<Assignment>()
.HasMany(m => m.Responsibles)
.WithMany()
.Map(m =>
{
m.MapLeftKey("AssignmentId");
m.MapRightKey("UserId(Responsible)");
m.ToTable("AssignmentResponsibles");
});
modelBuilder.Entity<Assignment>()
.HasMany(m => m.Debtors)
.WithMany()
.Map(m =>
{
m.MapLeftKey("AssignmentId");
m.MapRightKey("UserId(Debtor)");
m.ToTable("AssignmentDebtors");
});
}
是否有一种方法可以在债务人和责任人列表中保持相同的用户实例?
因为当我试图保存更改时,我得到了错误。
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
我需要这样做,因为这是应用程序逻辑所要求的。
提前感谢。
更新:
在HttpPost上出现错误(在控制台应用程序示例中出现相同的错误):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Text,CreationDate,InititatorId,Debtors,Responsibles")] Assignment assignment)
{
if (ModelState.IsValid)
{
assignment.Debtors.RemoveAll(r => r.Name == "Roman");
db.Entry(assignment).State = EntityState.Modified; // HERE!
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.InititatorId = new SelectList(db.Users, "Id", "Name", assignment.InititatorId);
return View(assignment);
}
视图中的负债者和责任者元素通过隐藏输入传递。
为什么不直接获取数据,而不是直接将其附加到dbcontext中,具有相同id的相同赋值可能已经在相同上下文中本地附加了。
而不是这些
assignment.Debtors.RemoveAll(r => r.Name == "Roman");
db.Entry(assignment).State = EntityState.Modified; // HERE!
db.SaveChanges();
试试这些
var assignmentDb = db.Assignments.FirstOrDefault(asg => asg.Id == assignment.Id);
assignmentDb.Debtors.RemoveAll(r => r.Name == "Roman");
db.SaveChanges();