Model bazy danych utworzonych przez EntityFramework
wygląda tak, że każdy użytkownik ma listę książek, oraz jedną ulubioną:
public class User
{
public int Id { get; set; }
public string Name {get; set;}
public ICollection<Book> Books { get; set; }
public Book FavouriteBook { get; set; }
}
public class Book
{
public int Id { get; set; }
public string Title {get; set;}
}
Dodanie użytkownika z listą książek bez ulubionej wykona się poprawnie:
var book1 = new Book()
{
Title = "book1"
};
var book2 = new Book()
{
Title = "book2"
};
var user = new User()
{
Name = "user",
};
user.Books = new List<Book>() { book1, book2 };
context.Users.Add(user);
context.SaveChanges();
Natomiast gdy spróbuję dodać użytkownika, który posiada listę książek i jedną ulubioną:
user.Books = new List<Book>() { book1, book2 };
user.FavouriteBook = book2;
context.Users.Add(user);
context.SaveChanges();
To rzucany jest wtedy wyjątek:
System.Data.Entity.Infrastructure.DbUpdateException HResult=0x80131501 Message=An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.
Inner Exception 1: UpdateException: Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
Zamiarem było to, by dodały się 2 książki (book1
, oraz book2
), a ten sam rekord w bazie dotyczący book2
będzie przypisany do użytkownika, jako ulubiona książka.
Co tutaj jest nie tak?