Home > Net >  Entity Framework overwrites a foreign key from another record
Entity Framework overwrites a foreign key from another record

Time:07-29

This is just an example so you can understand, this is a system with people and their favorite books.

This is what the models look like:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Book> favBooks { get; set; }
}

public class Book
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int PageCount { get; set; }
}

My problem is if I add a book and 2 people and both have this as a FAV book, then one person is overwritten.

Book mathForDummies = new Book()
{
     Name = "Math for Dummies",
     PageCount = 457
};
            
_db.book.Add(mathForDummies);
_db.SaveChanges();

Person lena = new Person()
{
     Name = "Lena",
     favBooks = new List<Book>
     {
          mathForDummies
     }
};

Person max = new Person()
{
     Name = "Max",
     favBooks = new List<Book>
     {
          mathForDummies
     }
};
            
_db.person.Add(lena);
_db.person.Add(max);

_db.SaveChanges();

In this case, both have this book, but max overwrites lena.

person-table book-table

Is there a better way, or am I overlooking something?

CodePudding user response:

Your problem is not with Entity Framework itself, but with your database schema: your list is a n-to-one (or many-to-one) relationship and you need a n-to-n (or many-to-many).

Since book table has only one PersonId column (maybe it has a different name), each book can only be associated with one person at a time. To create a n-to-n relationship, you'll need a join table (that have BookId and PersonId columns).

Look this link to see how to configure it.

  • Related