Home > Software engineering >  How can i use UserManager with custom user?
How can i use UserManager with custom user?

Time:09-22

I have created custom user class which inherits IdentityUser<int>.

[Table("Users", Schema = "UserData")]
public class User : IdentityUser<int>
{
    /// <summary>
    /// Property for sake of creating One-to-One relationship UserDetails -> User
    /// </summary>
    [Required]
    public UserDetails UserDetails { get; set; }
}

public class BlogDbContext : IdentityDbContext<User, IdentityRole<int>, int>
    {
        public BlogDbContext(DbContextOptions<BlogDbContext> options)
                   : base(options) {}

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());

            //UserDataConfig
            builder.ApplyConfiguration(new UserConfiguration());
            builder.ApplyConfiguration(new UserDetailsConfiguration());


            //UserData

            builder.Entity<Location>()
                .HasOne<UserDetails>(s => s.UserDetails)
                .WithOne(g => g.Location)
                .HasForeignKey<UserDetails>(ad => ad.LocationId);

            builder.Entity<User>()
                .HasOne<UserDetails>(s => s.UserDetails)
                .WithOne(g => g.User)
                .HasForeignKey<UserDetails>(ad => ad.UserId);
   
            base.OnModelCreating(builder);
        }

        //UserData
        public DbSet<User> Users { get; set; }
        public DbSet<UserDetails> UserDetails { get; set; }
    }
}

Now I am trying to create following field

private UserManager<User, int> _userManager;

And my error:

The type 'ApplicationCore.DataModel.UserData.User' cannot be used as type parameter 'TUser' in the generic type or method 'UserManager<TUser, TKey>

enter image description here

How can I fix it? Thanks for your attention.

CodePudding user response:

Replace User to IdentityUser and Role to IdentityRole and working fine. like

public class DataContext : IdentityDbContext<IdentityUser,IdentityRole, string, IdentityUserClaim<string>, IdentityUserRole<string>,
       IdentityUserLogin<string>, IdentityRoleClaim<string>,IdentityUserToken<string>>

Or use:-

public class ApplicationUser : IdentityUser<int>
{
}
public class ApplicationRole : IdentityRole<int>
{
}
public class BlogDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>
{
}

It will resolve your issue.

  • Related