我使用Identity 2.0创建了一个MVC 5站点。我使用整数作为主键。
当我尝试创建一个与ApplicationUser关联的Model时,我收到以下错误:
EntityType'ApplicationUserRole'没有定义键。
我需要做些什么才能解决此错误?
IdentityModels.cs
public class ApplicationUserLogin : IdentityUserLogin<int> { }
public class ApplicationUserClaim : IdentityUserClaim<int> { }
public class ApplicationUserRole : IdentityUserRole<int> { }
public class ApplicationRole : IdentityRole<int, ApplicationUserRole>, IRole<int>
{
public string Description { get; set; }
public ApplicationRole() : base() { }
public ApplicationRole(string name) : this()
{
this.Name = name;
}
public ApplicationRole(string name, string description) : this(name)
{
this.Description = description;
}
}
public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
public string FullName { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
Employee.cs
public class Employee
{
public int Id { get; set; }
public string Title { get; set; }
public virtual ApplicationUser User { get; set; }
}
答案 0 :(得分:3)
您需要覆盖OnModelCreating方法以定义主键:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ApplicationUserLogin>().HasKey<int>(l => l.UserId);
modelBuilder.Entity<ApplicationRole>().HasKey<int>(r => r.Id);
modelBuilder.Entity<ApplicationUserRole>().HasKey(r => new { r.RoleId, r.UserId });
}
这是一个类似的主题:User in Entity type MVC5 EF6