Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attempted to update or delete an entity that does not exist in the store

I am having a problem with EF Core 3.x and One-To-Many navigation properties which I did not have in previous versions.

Consider the following code:

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; }

}

In previous EF version (such as 2.2), the following could be done:

var book = new Book();
context.Books.Add(book);
context.SaveChanges();
book = context.Books.First();
var author = new Author();
book.Authors.Add(author);
context.SaveChanges();

Now, the same code, after updating to EF Core 3.x, throws the following exception at the last SaveChanges() call, and I really can't figure out why:

'Attempted to update or delete an entity that does not exist in the store.'

If I check the DbContext's ChangeTracker, I indeed see that the Author entity is marked as Modified instead of Added.

The following, however, works fine:

  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();

What is happening? I read about possibly breaking changes in 3.x, but did not find the mention/solution to this problem. Anyone has an idea?

Thanks in advance!

like image 278
Charles d'Avernas Avatar asked Dec 19 '19 16:12

Charles d'Avernas


1 Answers

So, crawling on google further made me land on this post: Owned Entity marked as detached when adding to a collection when the entities primary key is set

It appears to be a bug, that I could solve by using the following entity configuration, as ajcvickers suggested in the post linked above:

modelBuilder.Entity<Author>().Property(e => e.Id).ValueGeneratedNever();
like image 117
Charles d'Avernas Avatar answered Nov 20 '22 12:11

Charles d'Avernas