Entity Framework – Code First – Many to Many Relationship

Here is a simple example of code first many to many relationship.  A user can have multiple roles and a role can have multiple users.

public class Role
{
public int Id { get; set; }

[Required]
[MaxLength(50)]
public string RoleName { get; set; }

public virtual ICollection<User> Users { get; set; }
}

public class User
{
public int Id { get; set; }

[Required]
[MaxLength(100)]
public string Email { get; set; }

[Required]
[MaxLength(50)]
public string Password { get; set; }

public virtual ICollection<Role> Roles { get; set; }
}

The virtual property Users in class Role and the virtual property Roles in class User help establish a many to many relationship. 

In fact, entity framework will generate a association table UserRole for you.

public override void Up()
{
CreateTable(
"dbo.Role",
c => new
{
Id = c.Int(nullable: false, identity: true),
RoleName = c.String(nullable: false, maxLength: 50),
})
.PrimaryKey(t => t.Id);

CreateTable(
"dbo.User",
c => new
{
Id = c.Int(nullable: false, identity: true),
Email = c.String(nullable: false, maxLength: 100),
Password = c.String(nullable: false, maxLength: 50),
})
.PrimaryKey(t => t.Id);

CreateTable(
"dbo.UserRole",
c => new
{
User_Id = c.Int(nullable: false),
Role_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.User_Id, t.Role_Id })
.ForeignKey("dbo.User", t => t.User_Id, cascadeDelete: true)
.ForeignKey("dbo.Role", t => t.Role_Id, cascadeDelete: true)
.Index(t => t.User_Id)
.Index(t => t.Role_Id);

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s