I have a problem when I try to save the same object to different foreign properties.
This is my database context configuration:
public class ConfigurationContext : DbContext
{
public ConfigurationContext() : base("conn")
{
}
public DbSet<User> Users { get; set; }
public DbSet<Book> Books { get; set; }
}
Database models:
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;}
}
This is how I add new data:
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();
Everything works, but when I try to add favourite book like this:
user.Books = new List<Book>() { book1, book2 };
user.FavouriteBook = book2;
context.Users.Add(user);
context.SaveChanges();
Then this exception is thrown:
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.
What's wrong there?