ApplicationUser类型不能用作类型参数&#39; TUser&#39;在泛型类型或方法中,IdentityDbContext <tuser>&#39;

时间:2018-04-12 05:43:08

标签: c# asp.net-identity asp.net-core-2.0

尝试在ASP.NET Core 2.0中实现Identity。我遇到很多问题。

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("Ctrack6_Custom"))
        );


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

etc...

ApplicationUser.cs 使用Guid作为密钥。也可以在角色等中设置

// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser<Guid>
{
    [MaxLength(50)]
    public string FirstName { get; set; }

    [MaxLength(50)]
    public string LastName { get; set; }

    [MaxLength(5)]
    public string OrgCode { get; set; }

    public ApplicationUser() : base()
    {

    }

}

ApplicationDbContext.cs 在类定义中的此文件中引发错误。 ApplicationDbContext抛出此错误:

  

类型&#39; App.Identity.ApplicationUser&#39;不能用作类型参数&#39; TUser&#39;在泛型类型或方法中#IdentityDbContext&#39; App.Identity.ApplicationUser&#39; App.Identity.ApplicationUser&#39;没有隐式参考转换。到&#39; Microsoft.AspNetCore.Identity.IdentityUser&#39;。

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
        builder.Entity<blah>()
        .HasKey(c => new { fields, for, key });

    }

    public DbSet<etc> Etcs {get; set; }

}

1 个答案:

答案 0 :(得分:6)

更改public class ApplicationDbContext : IdentityDbContext<ApplicationUser>

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>

您需要具有与ApplicationUser类类似的ApplicationRole类。从我记忆中指定密钥类型(在本例中为Guid,默认为字符串)后,即使您没有使用角色,也需要包含角色和密钥类型。