我正在使用Microsoft.AspNet.Identity 2.0.0-beta1和Entity Framework 6.1.0-beta1(2014年2月11日发布).
当我尝试将用户ID主键的默认类型从字符串更改为int时以及当我尝试使用自定义表名(因此User.MyUsers而不是dbo.AspNetUsers)时,我收到以下错误:
“实体类型’IdentityUser’和’ApplicationUser’不能共享表’MyUsers’,因为它们不在同一类型层次结构中,或者没有有效的一对一外键关系,它们之间具有匹配的主键.”
我可以成功地将用户ID PK的默认类型从字符串更改为int或更改默认的标识表名称,但我不能同时执行这两个操作而不会出现此错误.
我的解决方案基于:
1:从http://blogs.msdn.com/b/webdev/archive/2013/12/20/announcing-preview-of-microsoft-aspnet-identity-2-0-0-alpha1.aspx开始的“使用户和角色的主键类型可扩展”部分.
2:How can I change the table names when using Visual Studio 2013 ASP.NET Identity?.
我的实际代码是:
using Microsoft.AspNet.Identity.EntityFramework; namespace Musetone.Models { public class ApplicationUser : IdentityUser<int,CustomUserLogin,CustomUserRole,CustomUserClaim> { } public class CustomRole : IdentityRole<int,CustomUserRole> { public CustomRole() { } public CustomRole(string name) { Name = name; } } public class CustomUserRole : IdentityUserRole<int> { } public class CustomUserClaim : IdentityUserClaim<int> { } public class CustomUserLogin : IdentityUserLogin<int> { } public class ApplicationDbContext : IdentityDbContext<ApplicationUser,CustomRole,int,CustomUserClaim> { public ApplicationDbContext() : base("DefaultConnection") { } protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<IdentityUser>().ToTable("MyUsers","User").HasKey(u => u.Id).Property(u => u.Id).HasColumnType("int"); modelBuilder.Entity<ApplicationUser>().ToTable("MyUsers","User").HasKey(u => u.Id).Property(u => u.Id).HasColumnType("int"); modelBuilder.Entity<IdentityUserRole>().ToTable("MyUserRoles","User").HasKey(r => new { r.RoleId,r.UserId }).Property(r => r.UserId).HasColumnType("int"); modelBuilder.Entity<IdentityUserLogin>().ToTable("MyUserLogins","User").HasKey(l => new { l.UserId,l.LoginProvider,l.ProviderKey }).Property(l => l.UserId).HasColumnType("int"); modelBuilder.Entity<IdentityUserClaim>().ToTable("MyUserClaims","User").Property(c => c.UserId).HasColumnType("int"); modelBuilder.Entity<IdentityRole>().ToTable("MyRoles","User").HasKey(r => r.Id); } } }
即使我删除HasColumnType(“int”),我也会收到此错误.
任何帮助将不胜感激.
解决方法
我认为映射可能不正确.在定义ApplicationDbContext类时,您使用为通用的角色,登录和声明定义的自定义类,但是传递用于映射表的基类.对于ChangePK示例,以下映射对我有用.如果这也适合你,请告诉我.映射应该足够简单
protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<ApplicationUser>().ToTable("MyUsers"); modelBuilder.Entity<CustomUserRole>().ToTable("MyUserRoles"); modelBuilder.Entity<CustomUserLogin>().ToTable("MyUserLogins"); modelBuilder.Entity<CustomUserClaim>().ToTable("MyUserClaims"); modelBuilder.Entity<CustomRole>().ToTable("MyRoles"); }