Search code examples
c#ef-code-first

Howto config Code First Entity Framework Many-to-Many mapping table?


From examples that I have seen online and in a Programming Entity Framework CodeFirst book, when you have a collection on both classes EF would create a mapping table with two primary keys. But how can I add some extra fields to this table? For example, I have following entities and context:

public class User
{
    [Key]
    public Guid Id { get; set; }
    public String Name { get; set; }
    public virtual ICollection<Role> Roles { get; set; }
}

public class Role
{
    [Key]
    public Guid Id { get; set; }
    public String Name { get; set; }
    public virtual ICollection<User> Users { get; set; }
}

class MyContext : DbContext
{
    public MyContext (string connString)
        : base(connString)
    {
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }
}

Accessing this context will result in creating database with 3 tables: Users, Roles And UserRoles - Many-to-Many mapping table with two Guid Fields.

I want to add some extra field to this table - DateTime AssignmentDate. If I add new entity

public class UserRoles
{
    [Key]
    public Guid User_Id { get; set; }
    [Key]
    public Guid Role_Id { get; set; }
    public DateTime AssignmentDate { get; set; }
}

class MyContext : DbContext
{
    public MyContext (string connString)
        : base(connString)
    {
    }

    public DbSet<User> Users { get; set; }
    public DbSet<Role> Roles { get; set; }
    public DbSet<UserRoles> UserRoles { get; set; }
}

The result is one extra table in database. But I want to modify automatically created table. How can I do this?


Solution

  • You have to use the separate class UserRoles but in your User and Role classes change the relationship to use IList<UserRole> instead of referencing one another directly.

    You can't config the default many-to-many table since it is always autogenerated with just the two primary key columns.