5

I have two entities with many to many relationship like this:

class author
{
  public int AuthorID{get;set;}
  public string Name{get;set;}
  public virtual ICollection<book> books{get;set;}
}
class book
{
  public int BookID{get;set;}
  public string Name{get;set;}
 public virtual ICollection<author> authors{get;set;}

}

and I have an intermediate table named Bookauthor defined like this:

  BookAuthor: int
  int AuthorID
  int BookID

How to map this using FluentAPI

Thanks!!

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670

2 Answers2

8

This was problematic with EDMX but with EF 4.1 fluent API you can map it:

modelBuilder.Entity<book>()
            .HasMany(b => b.authors)
            .WithMany(a => a.books)
            .Map(m => m.MapLeftKey("BookID")
                   .MapRightKey("AuthorID")
                   .ToTable("BookAuthor"));

As you can see I don't map BookAuthor column. That column is unknown to EF and must be auto incremented.

This obviously can't work with a Code-first approach but only if you use Fluent API against existing database.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • it is working? really? with which condition? 4.1 doesnt care about OnModelCreating override. I am really living shock. ToTable("BookAuthor") doesn't create a table which is call by BookAuthor. – Nuri YILMAZ Aug 19 '11 at 13:31
0

I don't think EF allows you to have a separate Id in many-to-many junction tables.

The alternative is just mapping BookAuthor as an entity.

On a side note, NHibernate supports this construct using an idbag

Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154