ASP.NET MVC标识用户的外键

时间:2015-05-18 07:45:56

标签: c# asp.net asp.net-mvc

我已经在stackoverflow上阅读了所有内容但无法管理我的错误:

 public class Album
  {
    public int AlbumId { get; set; }
    public String Name { get; set; }
    public String Description { get; set; }
    public virtual ApplicationUser User { get; set; }
  }

  public class ApplicationUser : IdentityUser
    {
    public virtual ICollection<Album> Albums { get; set; }
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<Album> Albums { get; set; }

    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
        Configuration.LazyLoadingEnabled = true;
        Configuration.ProxyCreationEnabled = false;
        Database.SetInitializer<ApplicationDbContext>(new CreateDatabaseIfNotExists<ApplicationDbContext>());
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

得到了:

在模型生成期间检测到一个或多个验证错误:

photoManager.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
photoManager.Models.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined.
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.

我被困了!!! 所以请帮助。有什么问题?

1 个答案:

答案 0 :(得分:0)

需要注意两件事

  1. 检查您正在使用的DbContext。情况可能是您可以拥有多个上下文并且您正在使用尚未正确初始化的上下文

  2. 尝试更新OnModelCreating:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
        modelBuilder.Entity<IdentityRole>().HasKey<string>(r => r.Id);
        modelBuilder.Entity<IdentityUserRole>().HasKey(r => new { r.RoleId, r.UserId });
    }
    
  3. 如果您还没有

    ,可以参考以下内容

    1。Modify DbContext

    2。Change ModelBinding

    3。Change ModelBinding(Tricky)