Search code examples
entity-frameworkcode-first

Entity Framework Specifying Multiplicity


I'm currently using entity framework code first with the following models (please refer below). 1 Category can contain many books and similarly 1 rental can also have many books.

public class Book {
    public Guid Id {get; set;}
    public string Title {get; set;}

    public virtual BookCategory Category {get; set;}
}

public class BookCategory {
    public Guid Id {get; set;}
    public string Name {get; set;}

    public virtual ICollection<Book> Books {get; set;}
}

public class Rental {
    public Guid Id {get; set;}
    public DateTime DateRented {get; set;}

    public virtual ICollection<Book> Books {get; set;}
}

When I generate the DB, what I'm getting is the book table with both BookCategory_Id and Rental_Id.

Book Table

| Id | Title | BookCategory_Id | Rental_Id |

However this will not work in my context as multiple rental can contain the same book. Is there a way where I can specify the relationship so entity framework will generate a new table which contains something as follows:

Rental_Book Table

| Rental_Id | Book_Id |
|    aaa    |  book1  |
|    aaa    |  book2  |
|    bbb    |  book1  |

Any help?


Solution

  • Yes, you can do that creating a many-to-many relationship between Rental and Book entities. In the Book entity add a Rentals collection navigation property:

    public class Book {
        public Guid Id {get; set;}
        public string Title {get; set;}
    
        public virtual BookCategory Category {get; set;}
        public virtual ICollection<Rental> Rentals {get; set;}
    }
    

    Then, add this configuration in the OnModelCreating method of your context:

     protected override void OnModelCreating(DbModelBuilder modelBuilder)
     {
    
           modelBuilder.Entity<Book>()
                       .HasMany<Rental>(b => b.Rentals)
                       .WithMany(r => r.Books)
                       .Map(cs =>
                                {
                                    cs.MapLeftKey("Book_Id");
                                    cs.MapRightKey("Rental_Id");
                                    cs.ToTable("Rental_Books");
                                });
    
      }
    

    For more info about this kind of relationship check this link