ASP.. NET MVC用户标识外键
本文关键字:用户标识 MVC NET ASP | 更新日期: 2023-09-27 17:49:35
我已经阅读了所有的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.
我卡住了!所以请帮忙。怎么了?
有两点需要注意
-
检查您正在使用的DbContext。有可能你可以有多个上下文而你使用的上下文还没有正确初始化
-
尝试更新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 }); }
如果您还没有
,您可以参考以下内容。1。修改DbContext
2。改变ModelBinding
3。改变ModelBinding(复杂的)