EF 4.1 RC Many to many relationship in EF CF

故事扮演 提交于 2019-12-09 06:34:59

问题


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!!


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/5561652/ef-4-1-rc-many-to-many-relationship-in-ef-cf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!