James James - 1 year ago 104
ASP.NET (C#) Question

Why does this violate the type constraint?

I'm trying to customise ASP.NET Identity 3 so that it uses integer keys:

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) {
_created = true;

This compiles okay, but then throws a runtime error:


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

The signature for

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>

is precisely an
. Isn't this what it's looking for?

Answer Source

Ran into this problem. It was crashing on the startup.cs file. changed

services.AddIdentity<ApplicationUser, ApplicationIdentityRole>()


services.AddIdentity<ApplicationUser, ApplicationIdentityRole>()

declaring the key type seemed to get past the crash

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download