实体框架代码第一成员资格提供者关系问题

时间:2013-02-20 17:28:00

标签: entity-framework ef-code-first asp.net-membership

我正在尝试首先在asp.net会员提供商上编码。当代码首次创建表时,它会生成所有表和桥表的适当关系,但它也会创建从AspNet_User(一个)到Aspnet_Role(很多)的附加关系。你知道为什么这样做吗?用户和角色表之间不应该有任何关系。

public class Aspnet_Role
{
    public Aspnet_Role()
    {
        Aspnet_Users = new HashSet<Aspnet_Users>();
    }
    [Key]
    public Guid RoleId { get; set; }
    public string RoleName { get; set; }
    public string LoweredRoleName { get; set; }
    public string Description { get; set; }

    public virtual ICollection<Aspnet_Users> Aspnet_Users { get; set; }
}
public class Aspnet_Users
{
    public Aspnet_Users()
    {
        Aspnet_Roles = new HashSet<Aspnet_Role>();
    }
    [Key]
    public Guid UserId { get; set; }
    public string UserName { get; set; }
    public string LoweredUserName { get; set; }
    public string MobileAlias { get; set; }
    public bool IsAnonymous { get; set; }
    public DateTime LastActivityDate { get; set; }

    public virtual Aspnet_Membership Aspnet_Membership { get; set; }
    public virtual ICollection<Aspnet_Role> Aspnet_Roles { get; set; }
}
public class StagingContext : DbContext
{
    public DbSet<Aspnet_Role> Aspnet_Roles { get; set; }
    public DbSet<Aspnet_Users> Aspnet_Users { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)

    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Aspnet_Users>()
            .HasMany(r => r.Aspnet_Roles)
            .WithMany()
            .Map(m => m.ToTable("aspnet_UsersInRoles")
                .MapRightKey("RoleId")
                .MapLeftKey("UserId"));

    }
}

1 个答案:

答案 0 :(得分:0)

我在WithMany扩展名上添加了导航属性。

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

     modelBuilder.Entity<Aspnet_Users>()
         .HasMany(r => r.Aspnet_Roles)
         .WithMany(u => u.Aspnet_Users)
         .Map(m => m.ToTable("aspnet_UsersInRoles")
         .MapRightKey("RoleId")
          .MapLeftKey("UserId")); 

}