Arv*_*vis 2 entity-framework entity-framework-6 asp.net-identity
一切顺利,直到我决定将IdentityUser集合添加到另一个实体作为导航属性.
在模型生成期间检测到一个或多个验证错误:
IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
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.
Run Code Online (Sandbox Code Playgroud)
但它们是Microsoft.AspNet.Identity.EntityFramework库的一部分.他们怎么没有定义键?
我的实体和数据库上下文(EF v6.1,AspNet.Identity v.2.0):
public class User : IdentityUser
{
public virtual int OrganizationId { get; set; }
public virtual Organization Organization { get; set; }
}
public class Organization
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class DatabaseModelContext : IdentityDbContext<User>
{
public DatabaseModelContext() : base("ConnectionString") { }
public DbSet<Organization> Organizations { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
还尝试定义显式关系:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Organization>()
.HasMany(o => o.Users)
.WithOptional(u => u.Organization)
.HasForeignKey(u => u.OrganizationId);
modelBuilder.Entity<User>()
.HasOptional(u => u.Organization)
.WithMany()
.HasForeignKey(u => u.OrganizationId);
}
Run Code Online (Sandbox Code Playgroud)
没有成功!
它不能只是,必须为实体框架内部类定义关键类型!
解决方案(更新)
实际上我的简化示例并未反映我的真实应用情况.我很抱歉.我一直在我的应用程序中使用多个Dbcontexts,组织实体来自Dbcontext类派生的单独上下文.通过这种方式,此上下文对IdentityUser模型一无所知,但组织实体涉及用户实体 - 存在问题.
解决方案 - 我从IdentityDbContext派生了我所有的其他上下文!
实际上我的简化示例并未反映我的真实应用情况.我很抱歉.我一直在我的应用程序中使用多个Dbcontexts,组织实体来自Dbcontext类派生的单独上下文.通过这种方式,此上下文对IdentityUser模型一无所知,但组织实体涉及用户实体 - 存在问题.
解决方案 - 我从IdentityDbContext派生了我所有的其他上下文!
| 归档时间: |
|
| 查看次数: |
899 次 |
| 最近记录: |