How to model a scenario where the bridge table has an attribute as well RRS feed

  • Question

  • I am reading the entity framework tutorial and was able to understand how to write many to many relationships.

    In my case I have two entities which have many to many relationship.

    Site (Id, Name)

    User(Id, Name)

    So a site can have many users and a user can have many sites.

    The catch is that the bridge table has an attribute called "IsAdmin"

    SiteUserMap (SiteId, UserId, IsAdmin)

    How will you model this in entity framework code first approach?

    val it: unit=()

    Friday, May 9, 2014 5:51 AM


  • Hello,

    >>How will you model this in entity framework code first approach?

    By the automatically generated junction table, it is impossible to customize the table with a many to many relationship.

    For mapping many to many relationship with additional fields in Code First, the main idea is that we need to create two one to many relationships, it does not matter whether we use the EntityTypeConfiguration class or OnModelCreating() method:

    ObjectOne : ObjectOneObjectTwo => N:1, ObjectTwo : ObjectOneObjectTwo => N:1,

    Then it needs us to add a collection type in both ObjecOne and ObjectTwo classes as:

    public virtual ICollection<ObjectOneObjectTwo> ObjectOneObjectTwos{ get; set; }

    In the EntityTypeConfiguration class of the junction table, to define ObjectOneId, ObjectTwoId, AddedDate these three columns to be primary key.

    In the EntityTypeConfiguration classes of ObjectOne and ObjectTwo, to define the one to many relationship between ObjectOne/ObjectTwo with ObjectOneObjectTwo and specify the foreign key.


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by Fred Bao Monday, May 19, 2014 6:15 AM
    Friday, May 9, 2014 7:52 AM