Search code examples
c#asp.net-coreasp.net-identity-3

'MyIdentityModels.User' violates the constraint of type 'TUser'


I'm trying to customize ASP.NET Identity Core and I'm getting the following exception: (It Seems to build fine but it crashes even before launching)

Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: GenericArguments[0], 'Echap.Models.Models.Identity.User', on 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`4[TUser,TRole,TContext,TKey]' violates the constraint of type 'TUser'. ---> System.TypeLoadException: GenericArguments[0], 'Echap.Models.Models.Identity.User', on 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[TUser,TRole,TContext,TKey,TUserClaim,TUserRole,TUserLogin,TUserToken,TRoleClaim]' violates the constraint of type parameter 'TUser'.
   at System.RuntimeTypeHandle.Instantiate(RuntimeTypeHandle handle, IntPtr* pInst, Int32 numGenericArgs, ObjectHandleOnStack type)
   at System.RuntimeTypeHandle.Instantiate(Type[] inst)
   at System.RuntimeType.MakeGenericType(Type[] instantiation)
   --- End of inner exception stack trace ---
   at System.RuntimeType.ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception e)
   at System.RuntimeType.MakeGenericType(Type[] instantiation)
   at Microsoft.Extensions.DependencyInjection.IdentityEntityFrameworkBuilderExtensions.GetDefaultServices(Type userType, Type roleType, Type contextType, Type keyType)
   at Microsoft.Extensions.DependencyInjection.IdentityEntityFrameworkBuilderExtensions.AddEntityFrameworkStores[TContext,TKey](IdentityBuilder builder)
   at Echap.Startup.ConfigureServices(IServiceCollection services)
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.AspNetCore.Hosting.Internal.ConfigureServicesBuilder.Invoke(Object instance, IServiceCollection exportServices)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
   at Echap.Program.Main(String[] args)

As far as I know, I'm doing everything right, why is this happening?

public sealed class ApplicationDbContext : IdentityDbContext<User, Role, int, UserClaim, UserRole, UserLogin, RoleClaim, UserToken>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {
        try
        {
            Database.EnsureCreated();
        }
        catch (Exception e)
        {
        }
    }

    public DbSet<Category> Categories { get; set; }
    public DbSet<CategoryService> CategoryServices { get; set; }
    public DbSet<Coating> Coatings { get; set; }
    public DbSet<Corner> Corners { get; set; }
    public DbSet<Order> Orders { get; set; }
    public DbSet<Press> Presses { get; set; }
    public DbSet<PressData> PressDatas { get; set; }
    public DbSet<PressService> PressServices { get; set; }
    public DbSet<PrintedSide> PrintedSides { get; set; }
    public DbSet<PrintSize> PrintSizes { get; set; }
    public DbSet<Quantity> Quantities { get; set; }
    public DbSet<Service> Services { get; set; }
    public DbSet<ServiceCoating> ServiceCoatings { get; set; }
    public DbSet<ServiceCorner> ServiceCorners { get; set; }
    public DbSet<ServicePrintedSide> ServicePrintedSides { get; set; }
    public DbSet<ServicePrintSize> ServicePrintSizes { get; set; }
    public DbSet<ServiceQuantity> ServiceQuantities { get; set; }


    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);


        modelBuilder.Entity<User>().ToTable("Users");
        modelBuilder.Entity<Role>().ToTable("Roles");
        modelBuilder.Entity<UserRole>().ToTable("UserClaims");
        modelBuilder.Entity<UserRole>().ToTable("UserRoles");
        modelBuilder.Entity<UserLogin>().ToTable("UserLogins");
        modelBuilder.Entity<RoleClaim>().ToTable("RoleClaims");
        modelBuilder.Entity<UserToken>().ToTable("UserToken");
    }
}

Here is my User class:

public class User : IdentityUser<int, UserClaim, UserRole, UserLogin>
{
    public User()
    {
        Presses = new List<Press>();
    }

    public string TestField { get; set; }

    public virtual ICollection<Press> Presses { get; set; }
}

and here is my Role class:

public class Role : IdentityRole<int, UserRole, RoleClaim> {}

This is how I add identity in Startup.cs:

services.AddIdentity<User, Role>()
                .AddEntityFrameworkStores<ApplicationDbContext, int>()
                .AddDefaultTokenProviders();

Solution

  • I managed to fix the issue by making the following changes:

    User.cs

    public class User : IdentityUser<int>
    

    Role.cs

    public class Role : IdentityRole<int> {}
    

    ApplicationDbContext:

    public sealed class ApplicationDbContext : IdentityDbContext<User, Role, int>
    

    Also inside the ApplicationDbContext I added:

    modelBuilder.Entity<User>().ToTable("Users");
    modelBuilder.Entity<Role>().ToTable("Roles");
    modelBuilder.Entity<IdentityUserClaim<int>>().ToTable("UserClaims");
    modelBuilder.Entity<IdentityUserRole<int>>().ToTable("UserRoles");
    modelBuilder.Entity<IdentityUserLogin<int>>().ToTable("UserLogins");
    modelBuilder.Entity<IdentityRoleClaim<int>>().ToTable("RoleClaims");
    modelBuilder.Entity<IdentityUserToken<int>>().ToTable("UserToken");