Entity Framework, Code First, Multiplicity constraint violated

314 Views Asked by At

I am trying to get a User class to contain both a list of books and an optional favorite book. When calling SaveChanges() below, I get the error message

The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: Multiplicity constraint violated. The role 'User_FavoriteBook_Target' of the relationship 'ConsoleApplication1.User_FavoriteBook' has multiplicity 1 or 0..1."}

What I want to accomplish is to make the User table have a column which stores the Id of the favorite book. How can I do this?

public class User
{
    public int UserId { get; set; }
    public List<Book> Books { get; set; }
    public Book FavoriteBook { get; set; }
}

public class Book
{
    public int BookId { get; set; }
    public string Name { get; set; }
}

public class UserContext : DbContext
{
    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Configurations.Add(new UserConfiguration());
    }

public class UserConfiguration : EntityTypeConfiguration<User>
    {
        public UserConfiguration()
        {
            HasMany(e => e.Books).WithRequired().WillCascadeOnDelete();
            HasOptional(e => e.FavoriteBook).WithRequired().WillCascadeOnDelete(false);
        }
    }
}

Main program:

User user = new User();
Book book1 = new Book { Name = "book1" };
Book book2 = new Book { Name = "book2" };
user.Books.Add(book1);
user.Books.Add(book2);
user.FavoriteBook = book2;

using (UserContext context = new UserContext())
{
    context.Users.Add(user);
    context.SaveChanges();
}
0

There are 0 best solutions below