Entity Framework Code First 模式-建立多对多联系

Entity Framework 在建立多对多的联系时,会生成一个中间表,用来表示这个多对多的关系。这和数据库设计时从概念模型到逻辑模型转化时,多对多的关系不能和任何一端的实体合并,需要将关系也转化为关系模型。例子使用角色(Role)和用户(User),一个角色会有多个用户,一个用户拥有多个角色。

1.默认约定

代码:

public partial class Role
    {
        public int RoleID { get; set; }
        public string RoleName { get; set; }

        public virtual ICollection<User> Users { get; set; }
    }
public class User
    {
        public int UserID { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public Nullable<bool> IsValid { get; set; }

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

结果:

2.FluentAPI 方式

这边展示用映射类的方式去建立表,即为每个实体类去建立一个映射到数据库的类,在这里面定义映射到数据库的相关属性。

代码:

public partial class Role
    {
        public int RoleID { get; set; }
        public string RoleName { get; set; }

        public virtual ICollection<User> Users { get; set; }
    }
Role类
 public class RoleMap:EntityTypeConfiguration<Role>
    {
        public RoleMap()
        {
            //主键
            this.HasKey(s => s.RoleID);

            //属性的特性
            this.Property(s => s.RoleName)
                .HasMaxLength(15);

            //类映射到数据库表和列的相关说明
            this.ToTable("Role");
            this.Property(s => s.RoleID).HasColumnName("Id");

            //实体关系之间的定义
            this.HasMany(s => s.Users)
                .WithMany(s => s.Roles)
                .Map(m =>
                {
                    m.ToTable("RoleUser");
                    m.MapLeftKey("RoleId");
                    m.MapRightKey("UserID");
                });

        }
    }
RoleMap 映射类
public class User
    {
        public int UserID { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public Nullable<bool> IsValid { get; set; }

        public virtual ICollection<Role> Roles { get; set; }
    }
User 类
public UserMap()
        {
            //主键
            this.HasKey(s => s.UserID);

            //属性
            this.Property(s => s.UserName)
                .HasMaxLength(10);

            // //类映射到数据库表和列的相关说明
            this.ToTable("User");
            this.Property(s => s.UserName).HasColumnName("Name");
        }
UserMap 映射类

在数据上下文类中的OnModelCreating方法加入如下代码:

modelBuilder.Configurations.Add(new RoleMap());
modelBuilder.Configurations.Add(new UserMap());

结果:

原文地址:https://www.cnblogs.com/engineerlm/p/7608476.html