[英]Entity Framework overwrites a foreign key from another record
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.我的问题是,如果我添加一本书和 2 个人,并且都将这本书作为 FAV 书籍,那么一个人会被覆盖。
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.在这种情况下,两者都有这本书,但 max 覆盖了 lena。
Is there a better way, or am I overlooking something?有没有更好的方法,还是我忽略了什么?
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.由于book
表只有一个PersonId
列(可能名称不同),因此每本书一次只能与一个人关联。 To create a n-to-n relationship, you'll need a join table (that have BookId
and PersonId
columns).要创建 n 对 n 关系,您需要一个连接表(具有BookId
和PersonId
列)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.