问题描述
ASP.NET MVC 5,当涉及引用 ApplicationUser
实体的实体时,我在添加迁移时遇到了一些问题。我在创建项目时使用个人帐户进行身份验证。
public class Blog
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[ForeignKey("ApplicationUser")]
public string ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
[required]
[StringLength(500,ErrorMessage = "The {0} must be at least {2} characters long.")]
public string Content { get; set; }
}
public class ApplicationUser : IdentityUser
{
public bool IsSoftDeleted { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this,DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
}
而我的 DBContexts 是
public class ApplicationUserDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationUserDbContext()
: base("DefaultConnection",throwIfV1Schema: false)
{
}
public static ApplicationUserDbContext Create()
{
return new ApplicationUserDbContext();
}
}
public class BloggingServiceDbContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public BloggingServiceDbContext() : base("DefaultConnection")
{
}
}
我在包管理控制台上运行的脚本是:
Add-Migration InitialBlogMigration -ConfigurationTypeName BloggerConfiguration
我得到的错误是:
BloggingService.Web.Context.IdentityUserLogin:: EntityType 'IdentityUserLogin' 没有定义键。定义此 EntityType 的键。
BloggingService.Web.Context.IdentityUserRole:: EntityType 'IdentityUserRole' 没有定义键。定义此 EntityType 的键。
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' 基于未定义键的类型 'IdentityUserLogin'。
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' 基于未定义键的类型 'IdentityUserRole'。
注意:在实现 Blog
之前,运行 add-migration
没有问题,并且数据库不包含错误消息中提到的任何实体。
关于可能是什么问题,我已经没有线索了。你能帮我找出问题吗?
解决方法
解决方案似乎很简单,我需要将所有实体都放在将 ApplicationUser 引用到 ApplicationUserDbContext 的位置。但我仍然不知道为什么会这样,如果有人能为我澄清这一点就好了。