【问题标题】:Guid Instead of string for primary key / ID for ASP.Net Core 3.1 IdentityASP.Net Core 3.1 Identity 的主键/ID 的 Guid 而不是字符串
【发布时间】:2020-01-04 04:44:40
【问题描述】:

这不再适用于 ASP.Net Core 3.1 / .Net Core 3.1

https://stackoverflow.com/a/37173202/1698480

编译错误:“IdentityBuilder”不包含“AddEntityFrameworkStores”的定义,并且找不到接受“IdentityBuilder”类型的第一个参数的可访问扩展方法“AddEntityFrameworkStores”(您是否缺少 using 指令或程序集引用? ) WebSite.Site C:\WorkSource....\Startup.cs 32 活动

public class ApplicationUser : IdentityUser<Guid> { }
public class Role : IdentityRole<Guid> { }

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, Role, Guid>
{
   ...
}

public class Startup
{
    ...
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddIdentity<ApplicationUser, Role>()
            .AddEntityFrameworkStores<ApplicationDbContext, Guid>()
            .AddDefaultTokenProviders()
            .AddUserStore<UserStore<ApplicationUser, Role, ApplicationDbContext, Guid>>()
            .AddRoleStore<RoleStore<Role, ApplicationDbContext, Guid>>();

    }
}

如果我像这样删除 Guid 通用参数:

.AddEntityFrameworkStores<ApplicationDbContext, Guid>()

然后我得到浏览器错误:找不到这个本地主机页面没有找到网址的网页:http://localhost:50827/Account/Login?ReturnUrl=%2F

我该怎么做?谢谢

【问题讨论】:

标签: asp.net-core .net-core


【解决方案1】:

这第一部分就像以前一样:

public class ApplicationUser : IdentityUser<Guid> { }
public class Role : IdentityRole<Guid> { }

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, Role, Guid>
{
   ...
}

然后你像这样做剩下的事情:

public class Startup
{
    … 
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddIdentity<ApplicationUser, Role>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders()
            .AddUserStore<UserStore<ApplicationUser>>()
            .AddRoleStore<RoleStore<Role>>();

    }
}

请注意,ASP.NET Core 3.1 在弄清楚所有事情方面变得非常聪明,例如识别您正在使用 GUID 进行标识。你甚至不需要在你的Startup 中指定ApplicationDbContext 类型、ApplicationUser 类型和Role 类型;当你提到这些类时,它只是通过反射查找它们并自己找出细节。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多