gpt4 book ai didi

c# - 尝试更新或删除商店中不存在的实体

转载 作者:行者123 更新时间:2023-12-03 18:20:54 25 4
gpt4 key购买 nike

我在使用 EF Core 3.x 和一对多导航属性时遇到了问题,而我在以前的版本中没有这些属性。

考虑以下代码:

public class Book
{

public Book()
{
this.Id = Guid.NewGuid();
this.Authors = new List<Author>();
}

public virtual Guid Id { get; protected set; }

public virtual ICollection<Author> Authors { get; set; }

public void AddAuthor(Author author)
{
author.BookId = this.Id;
this.Authors.Add(author);
}

}

public class Author
{

public Author()
{
this.Id = Guid.NewGuid();
}

public virtual Guid Id { get; protected set; }

public virtual Guid BookId { get; set; }

public virtual Book Book { get; set; }

}

在以前的 EF 版本(例如 2.2)中,可以执行以下操作:
var book = new Book();
context.Books.Add(book);
context.SaveChanges();
book = context.Books.First();
var author = new Author();
book.Authors.Add(author);
context.SaveChanges();

现在,相同的代码在更新到 EF Core 3.x 后,在最后一次 SaveChanges() 调用时抛出以下异常,我真的不知道为什么:

“试图更新或删除商店中不存在的实体。”

如果我检查 DbContext 的 ChangeTracker,我确实看到 Author 实体被标记为已修改而不是已添加。

但是,以下工作正常:
  var book = new Book();
context.Books.Add(book);
context.SaveChanges();
book = context.Books.First();
var author = new Author() { BookId = book.Id };
context.Authors.Add(author);
context.SaveChanges();

怎么了?我阅读了 3.x 中可能发生的重大更改,但没有找到此问题的提及/解决方案。有人有想法吗?

提前致谢!

最佳答案

所以,在谷歌上爬行让我看到了这篇文章:
Owned Entity marked as detached when adding to a collection when the entities primary key is set

这似乎是一个错误,我可以通过使用以下实体配置来解决,如上面链接的帖子中建议的 ajcvickers :

modelBuilder.Entity<Author>().Property(e => e.Id).ValueGeneratedNever();

关于c# - 尝试更新或删除商店中不存在的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59413518/

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