0

下面是User实体的定义,有一个导航属性Roles

    public class User
    {
        public User()
        {
            Roles = new List<Role>();
        }

        public string Id { get; set; }

        public string Username { get; set; }

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

下面是角色实体的定义

public class Role
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

我想要的是定义多对多关系并生成一个关系表UserRole,它使用UserId作为左键,RoleId作为右键,那么如何编写配置代码?

4

1 回答 1

0

用户:

public class User
{
    public User()
    {
        Roles = new List<Role>();
    }

    public string Id { get; set; }
    public string Username { get; set; }
    public virtual ICollection<UserRole> Roles { get; set; }
}

角色:

public class Role
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

用户角色:

public class UserRole
{
    public string Id { get; set; }
    public string UserId { get; set; }
    public string RoleId{ get; set; }

    public virtual User User { get; set; }
    public virtual Role Role { get; set; }
}

覆盖OnModelCreatingdbcontext 中的方法:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<User>()
        .HasMany(c => c.Roles )
        .WithMany()                 
        .Map(x =>
        {
            x.MapLeftKey("UserId");
            x.MapRightKey("RoleId");
            x.ToTable("UserRoles");
        });
}
于 2017-04-06T03:20:22.350 回答