gpt4 book ai didi

many-to-many - SaveChanges() Entity Framework 4.1 的问题

转载 作者:行者123 更新时间:2023-12-04 05:28:56 25 4
gpt4 key购买 nike

我在将更改保存到数据库时遇到问题。

我正在我的 Controller 中更新模型 A,但是当我使用 SaveChanges() 保存更改时,我最终在 B 的数据库中有一个重复的项目。

调用 UpdateModel() 后,我检查了 Bs 属性,正如我预期的那样,但是在调用 SaveChanges() 之后,如果我检查 Bs 属性,我将看到 Id 完全不同(新 Id 和新输入)。

我的课是这样的:

public class A
{
[HiddenInput(DisplayValue = false)]
public int AId { get; set; }

public string Name { get; set; }

public virtual ICollection<B> Bs{ get; set; }
}

public class B
{
[HiddenInput(DisplayValue = false)]
public int BId { get; set; }

public string Name { get; set; }

public virtual ICollection<A> As{ get; set; }
}

我的 Controller 是这样的:

    [HttpPost]
public ActionResult Edit(A theA)
{
try
{
db.Entry(theA).State = EntityState.Modified;

foreach (var item in theA.Bs)
{
db.Entry(item).State = EntityState.Modified;
}

db.SaveChanges();

return RedirectToAction("Index");
}
catch
{
return View();
}
}

我做错了什么吗?

提前致谢

最佳答案

这是常见的行为。问题是 EF 不知道您附加了现有的 B 因此它会自动插入一条新记录。您必须通过调用 EF 说 B 是现有的:

// here add B to the collection in the A and after that call:
dbContext.Entry<B>(someB).State = EntityState.Unchanged();

或者在将 B 添加到 A 中的集合之前附加 B(我不确定在使用 UpdateModel 时是否可行ASP.NET MVC)。

dbContext.Bs.Attach(someB);
// now add B to the collection in the A

另一种可能性是先从数据库加载B,然后将加载的对象添加到A 中的集合,但这是到数据库的额外往返。

int id = someB.Id;
var loadedB = dbCotnext.Bs.Single(b => b.Id == id);
someA.Bs.Add(loadedB);
dbContext.As.Add(someA);
dbContext.SaveChanges();

结论:每次您调用 Add 时,整个对象图都会被跟踪为已插入,除非您先附加相关实体(在将它们添加到插入的父项之前 - 第二个和第三个示例)或者除非您手动添加父级后,将相关实体的状态更改回未更改。 (第一个例子)。

关于many-to-many - SaveChanges() Entity Framework 4.1 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5693571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com