efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Collection navigations should use reference equality by default

Open Anirie opened this issue 8 years ago • 3 comments

I encounter a strange behaviour while working with EF Core 2.1.1 .

You can find a small program for reproduction here: https://github.com/Anirie/EFCoreAddMethodBug

This code copies an existing "Book" entity with all it references.

In detail, it takes an existing “book”, resets the db connection (so the chosen book entity is untracked), deletes all key properties of the entity (including key properties of all children) and adds the entity to the context.

            var options = SqliteInMemory.CreateOptions<TestModelContext>();
            var dbContext = new TestModelContext(options);
            dbContext.Database.EnsureCreated();

            //create book with one page and one image ( image has navigation props to book and bookpage)
            var book = CreateBasicBook();
            var page = CreateBasicBookPage(book);
            var image = CreateBasicImage(book, page);

            dbContext.Add(book);
            dbContext.Add(page);
            dbContext.Add(image);
            dbContext.SaveChanges();

            //take existing book
            var bookToCopy =dbContext.Books.Include(b => b.BookPages).Include(b => b.Images).First() as Book;

            //reset Connection to Database
            dbContext.Dispose();
            dbContext = new TestModelContext(options);

            // set keyproperties to zero
            bookToCopy.Id = 0;
            //set keyproperties of children to zero
            foreach(var i in bookToCopy.Images)
            {
                i.Id = 0;
            }
            foreach(var p in bookToCopy.BookPages)
            {
                p.Id = 0;
            }

            //add to context
            dbContext.Add(bookToCopy);
            //save context
            dbContext.SaveChanges();

            //reset Connection to Database changes everything
            //dbContext.Dispose();
            //dbContext = new TestModelContext(options);

            //output
            var allBooks = dbContext.Books.Include(b => b.BookPages).Include(b => b.Images).ToList();
  
            Console.WriteLine("Initial Book: "+ JsonConvert.SerializeObject(allBooks[0], new JsonSerializerSettings
            {
               ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            }));
            Console.WriteLine("Copied Book: " + JsonConvert.SerializeObject(allBooks[1], new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            }));

Now the context contains two books (the initial book and its copy), but the copy holds two identical bookPages instead of one. Somehow, invoking dbContext.Add(bookToCopy) adds a second bookpage to the entity. **It seems that adding an entity with many references to the dbContext creates unwanted navigation properties.**I think that is not the intended behaviour of the dbContext.Add method. Strangely enough, if I reset the dbContext after I added the book entity everything works fine. That means, I get a context the contains the initial book, a copy of this book and all references are set in the right way. (For reproduction uncomment line 60 and 61 in the provided code)

Is it possible that the Add method contains a bug? Or is it intended to reset the DBConnection everytime after SaveChanges() method was invoked?

Steps to reproduce

You can finde the whole project here: https://github.com/Anirie/EFCoreAddMethodBug

Further technical details

EF Core version: 2.1.1 Database Provider: Microsoft.EntityFrameworkCore.Sqlite Operating system: Microsoft Windows 10 Pro IDE: Visual Studio 2017 15.4

Anirie avatar Aug 13 '18 14:08 Anirie

Note for triage: the issue here is that BookPage has overridden Equals\GetHashCode in an unstable way, causing the navigation property to not correctly identify duplicates. However, since EF is creating the navigation property instance, it should be creating it with reference comparison semantics, but this isn't happening.

@Anirie The way Equals/GetHashCode are overridden makes these types unsuitable for storage in a .NET collection since mutating members of the stored instance can change equality while the instance is being stored. This post by Eric Lippert has some good guidelines. You can work around this issue in EF Core by forcing the BookPages navigation property to use reference comparisons instead of your overridden Equals\GetHashCode:

public sealed class ReferenceEqualityComparer : IEqualityComparer<object>
{
    private ReferenceEqualityComparer()
    {
    }

    public static ReferenceEqualityComparer Instance { get; } = new ReferenceEqualityComparer();

    bool IEqualityComparer<object>.Equals(object x, object y) => x == y;

    int IEqualityComparer<object>.GetHashCode(object obj) => RuntimeHelpers.GetHashCode(obj);
}
...
public ICollection<BookPage> BookPages { get; set; }
    = new HashSet<BookPage>(ReferenceEqualityComparer.Instance);

However, you'll still need to be very careful using these objects elsewhere, so you may want to consider not overriding Equals\GetHashCode in this way.

ajcvickers avatar Aug 13 '18 20:08 ajcvickers

Thank you for your answer!! It helped a lot!

Anirie avatar Aug 14 '18 11:08 Anirie

fixed in aaa92d9d6f6fc20bb274f7b1afb20554bb20c96d

maumar avatar Oct 17 '18 22:10 maumar