21

我想自定義ASP.NET身份3,以便它使用整數鍵:這是爲什麼違反類型約束?

public class ApplicationUserLogin : IdentityUserLogin<int> { } 
public class ApplicationUserRole : IdentityUserRole<int> { } 
public class ApplicationUserClaim : IdentityUserClaim<int> { } 

public sealed class ApplicationRole : IdentityRole<int> 
{ 
    public ApplicationRole() { } 
    public ApplicationRole(string name) { Name = name; } 
} 

public class ApplicationUserStore : UserStore<ApplicationUser, ApplicationRole, ApplicationDbContext, int> 
{ 
    public ApplicationUserStore(ApplicationDbContext context) : base(context) { } 
} 

public class ApplicationRoleStore : RoleStore<ApplicationRole, ApplicationDbContext, int> 
{ 
    public ApplicationRoleStore(ApplicationDbContext context) : base(context) { } 
} 

public class ApplicationUser : IdentityUser<int> 
{ 
} 

public sealed class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int> 
{ 
    private static bool _created; 

    public ApplicationDbContext() 
    { 
    // Create the database and schema if it doesn't exist 
    if (!_created) { 
     Database.AsRelational().Create(); 
     Database.AsRelational().CreateTables(); 
     _created = true; 
    } 
    } 
} 

這將編譯好的,但隨後引發運行時錯誤:

System.TypeLoadException

GenericArguments[0], 'TeacherPlanner.Models.ApplicationUser', on 'Microsoft.AspNet.Identity.EntityFramework.UserStore`4[TUser,TRole,TContext,TKey]' violates the constraint of type parameter 'TUser'.

UserStore的簽名:

public class UserStore<TUser, TRole, TContext, TKey> 
where TUser : Microsoft.AspNet.Identity.EntityFramework.IdentityUser<TKey> 
where TRole : Microsoft.AspNet.Identity.EntityFramework.IdentityRole<TKey> 
where TContext : Microsoft.Data.Entity.DbContext 
where TKey : System.IEquatable<TKey> 

ApplicationUser恰恰是一個IdentityUser<int>。這不是它在尋找什麼?

+1

您是否意外地在您的項目中聲明瞭與IdentityUser同名的新類型?我有時候通過在CodeRush中選擇「declare type」而不是「add using statement」來做到這一點。 –

+0

不,只是檢查! – James

回答

45

跑進這個問題。它在startup.cs文件中崩潰。 改變

services.AddIdentity<ApplicationUser, ApplicationIdentityRole>() 
       .AddEntityFrameworkStores<ApplicationDbContext>() 
       .AddDefaultTokenProviders(); 

services.AddIdentity<ApplicationUser, ApplicationIdentityRole>() 
       .AddEntityFrameworkStores<ApplicationDbContext,int>() 
       .AddDefaultTokenProviders(); 

聲明密鑰類型似乎讓過去的碰撞

+0

我害怕我將不得不重寫所有的Identity類和方法,因爲我有很長的鍵,但是一切都適用於這個小小的修復。謝謝! – Atchitutchuk

9

就遇到了這個問題爲好。我不得不添加IdentityRole鍵類型,因爲它仍然拋出相同的錯誤。

 services.AddIdentity<ApplicationUser, IdentityRole<int>>() 
      .AddEntityFrameworkStores<ApplicationDbContext,int>() 
      .AddDefaultTokenProviders(); 
0

我現在得到了同樣的問題。修復是不同的。因此張貼在這裏。可能幫助別人。

services.AddIdentity<ApplicationUser, ApplicationRole>() 
     .AddEntityFrameworkStores<ApplicationDbContext,int>() 
     .AddDefaultTokenProviders(); 

我不得不創建一個空的類繼承ApplicationRoleIdentityRole<int>

public class ApplicationRole : IdentityRole<int> 
{ 

}