(C#, .NET)EFCore 多对多的表映射关系

如何在 .NET Core EF Core中实现多对多的表映射关系

首先创建两个实体与一个关联实体

    /// 
    /// 角色实体
    /// 
    public class Role
    {
        /// 
        /// 角色GUID
        /// 
        [Key]
        //[MaxLength(36)]
        [StringLength(36, MinimumLength =36)]
        [RegularExpression(Constants.GUID_REG, ErrorMessage =Constants.GUID_ERR)]
        public string Id { get; set; }

        /// 
        /// 角色名称
        /// 
        //[MaxLength(15)]
        [StringLength(15, MinimumLength = 2)]
        [RegularExpression(Constants.VISIBLE_REG, ErrorMessage =Constants.VISIBLE_ERR)]
        public string Name { get; set; }

        /// 
        /// 角色描述
        /// 
        [MaxLength(255)]
        public string Decription { get; set; }
        
        /// 
        /// 用户角色
        /// 
        [NotMapped]
        public List<UserRole> UserRoles { get; set; }
    }
    /// 
    /// 用户实体
    /// 
    public class UserBase
    {
        /// 
        /// 用户ID
        /// 
        [Key]
        [MaxLength(36)]
        [RegularExpression(Constants.GUID_REG, ErrorMessage = Constants.GUID_ERR)]
        public string Id { get; set; }

        /// 
        /// 用户签名
        /// 
        [MaxLength(15)]
        [RegularExpression(Constants.SIGNNAME_REG, ErrorMessage = Constants.SIGNNAME_ERR)]
        public string SignName { get; set; }

        /// 
        /// 用户密码
        /// 
        [MaxLength(63)]
        [RegularExpression(Constants.PASSWORD_REG, ErrorMessage = Constants.PASSWORD_ERR)]
        public string PassWord { get; set; }

        /// 
        /// 用户角色
        /// 
        [NotMapped]
        public List<UserRole> UserRoles { get; set; }
    }
    /// 
    /// 用户与角色关联
    /// 
    public class UserRole
    {
        /// 
        /// 关联ID
        /// 
        public string Id { get; set; }

        /// 
        /// 用户ID
        /// 
        public string UserId { get; set; }

        /// 
        /// 角色ID
        /// 
        public string RoleId { get; set; }

        /// 
        /// 用户
        /// 
        [NotMapped]
        [ForeignKey("UserId")]
        public UserBase User { get; set; }

        /// 
        /// 角色
        /// 
        [NotMapped] 
        [ForeignKey("RoleId")]
        public Role Role { get; set; }
    }

其次在DbContext中添加数据

    /// 
    /// 数据库上下文
    /// 
    public class ApplicationDbContext : DbContext
    {
        /// 
        /// 构造器
        /// 
        public ApplicationDbContext() { }

        /// 
        /// 应用数据库上下文
        /// 
        /// 
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options){ }

        #region << DbSet 数据集 >>

        /// 
        /// 用户数据集
        /// 
        public DbSet<UserBase> UserBases { get; set; }

        /// 
        /// 角色数据集
        /// 
        public DbSet<Role> Roles { get; set; }

        /// 
        /// 用户角色
        /// 
        public DbSet<UserRole> UserRoles { get; set; }

        #endregion

        /// 
        /// 在模型创建时
        /// 
        /// 
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            #region << 模型映射 >>

            builder.Entity<UserBase>(b =>
            {
                b.ToTable("userbase");
                b.HasIndex(p => p.SignName).IsUnique();
            });

            builder.Entity<Role>(b =>
            {
                b.ToTable("role");  //.HasIndex(prop=>prop.Name).IsUnique();
                //b.Property(p => p.Name);
                //b.Property(p => new { p.Name, p.Id });
            });

            builder.Entity<UserRole>(b =>
            {
                b.ToTable("userrole").HasKey(prop => new { prop.RoleId, prop.UserId });
                // 多对多关联 -外键在各个实体上用特性标识
                b.HasOne(ur => ur.User).WithMany(u => u.UserRoles);
                b.HasOne(ur => ur.Role).WithMany(r => r.UserRoles);
            });
            #endregion
        }

        /// 
        /// 数据库配置
        /// 
        /// 数据库上下文选项创建器
        protected override void OnConfiguring(DbContextOptionsBuilder builder)
        {
            base.OnConfiguring(builder);
            // Pomelo.EntityFrameworkCore.MySql 
            // TODO: 采用配置文件的方式
            builder.UseMySql("server=localhost;database=moretomore;user=admin;password=123456;");
        }
    }

你可能感兴趣的:(.NET,Core,EF,Core,数据库)