Entity Framework mappings to relational Relation Mapping (Entity Framework multi-to-Multi-link ing), entitymapping

Source: Internet
Author: User

Entity Framework mappings to relational Relation Mapping (Entity Framework multi-to-Multi-link ing), entitymapping

Generally, when we design a database, there will be two tables with many-to-many relationships. When the database has many-to-many relationships, we usually process them through intermediate join tables, so how do we deal with it in EF?

Assume that we have the following relationship: A User contains multiple roles. When a Role contains multiple users, how can we use EF to deal with such a database design?

Next, let's take a look at the following code list:

First, let's look at our User and Role entities.

 1 public class User 2  3 { 4  5     public User() {} 6  7   8  9     public int UserId { get; set; }10 11     public string Name { get; set; }12 13     public string Password { get; set; }14 15     public string PasswordSalt { get; set; }16 17     public Byte Status { get; set; }18 19     public DateTime CreatedDate { get; set; }20 21     public DateTime ModifiedDate { get; set; }22 23 }24 25 public class Role26 27 {28 29      public Role() {}30 31      public int RoleId { get; set; }32 33      public string RoleName { get; set; }34 35 }

Next, we know that a User contains multiple roles, so add such code to the User object.

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

 

Add this code to the User constructor.

this.Roles = new HashSet<Role>();

 

Similarly, a Role also contains multiple users, so add such code to the Role object

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

 

Add this code to the Role constructor.

this.Users = new HashSet<User>();

 

Next, construct the DataContext class inherited from the DbContext class.

public class DataContext : DbContext{    public DataContext()        : base("DataContext")    {    }    public DbSet<User> Users { get; set; }    public DbSet<Role> Roles { get; set; }    protected override void OnModelCreating(DbModelBuilder modelBuilder)    {            }}

 

Then, we generate our project and we can see the database relationships we have generated.

We can see that the link table in the middle generates User_UserId and Role_RoleId, but we may not define this in actual work or want to customize it more. Next we use the Fluent API (note: the literal translation here is a smooth API declaration. You can understand it literally, but I am not sure about it) to declare data. The link here isA user can contain multiple roles. A role can also contain multiple users.In the OnModelCreating method of DataContext, write as follows:

modelBuilder.Entity<User>()    .HasMany(r => r.Roles).WithMany(u => u.Users);

 

Further, we specify the intermediate chain table

 modelBuilder.Entity<User>()     .HasMany(r => r.Roles)     .WithMany(u => u.Users)     .Map(ur =>     {         ur.MapLeftKey("UserId");         ur.MapRightKey("RoleId");         ur.ToTable("UserRoles");     });

 

References:

Http://www.cnblogs.com/panchunting/p/entity-framework-code-first-fluent-api-configuring-relationships.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.