I am using Entity Framework to store objects of the following entity classes:
public class Library
{
public int Id { get; set; }
private ICollection<Book> _books;
public virtual ICollection<Book> Books => _books ?? (_books = new List<Book>());
}
public class Book
{
public int Id { get; set; }
public int LibraryId { get; set; }
public virtual Library Library { get; set; }
private ICollection<Page> _pages;
public virtual ICollection<Page> Pages => _pages ?? (_pages = new List<Page>());
}
public class Page
{
public int Id { get; set; }
public int BookId { get; set; }
public virtual Book Book { get; set; }
}
I want to be able to remove individual pages and books from the corresponding collections, so I do the following configuration with the fluent API:
modelBuilder.Entity<Library>()
.HasMany(library => library.Books)
.WithOptional()
.HasForeignKey(book => book.LibraryId);
modelBuilder.Entity<Book>()
.HasKey(book => new { book.Id, book.LibraryId })
.Property(book => book.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<Book>()
.HasMany(book => book.Pages)
.WithOptional()
.HasForeignKey(page => page.BookId);
modelBuilder.Entity<Page>()
.HasKey(page => new { page.Id, page.BookId })
.Property(page => page.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
I create composite keys for Book
and Page
and set up the one-to-many relationships.
When I try to create a migration I get the following error:
Book_Pages_Source_Book_Pages_Target: : The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical.
I suspect the error is on the foreign key of Page
, which should probably include LibraryId
, since it is part of the PK of Book
... How should I fix the configuration?