dan
dan

Reputation: 893

Guid Instead of string for primary key / ID for ASP.Net Core 3.1 Identity

This no longer works with ASP.Net Core 3.1 / .Net Core 3.1

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

Compile error:'IdentityBuilder' does not contain a definition for 'AddEntityFrameworkStores' and no accessible extension method 'AddEntityFrameworkStores' accepting a first argument of type 'IdentityBuilder' could be found (are you missing a using directive or an assembly reference?) WebSite.Site C:\WorkSource....\Startup.cs 32 Active

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>>();

    }
}

If I just remove the Guid generic arg like this:

.AddEntityFrameworkStores<ApplicationDbContext, Guid>()

then I get browser error: This localhost page can’t be foundNo webpage was found for the web address: http://localhost:50827/Account/Login?ReturnUrl=%2F

How can I do this? thanks

Upvotes: 1

Views: 2418

Answers (1)

ali tekrar
ali tekrar

Reputation: 71

This first part is just like before:

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

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

And then you do the rest like this:

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

    }
}

Note that ASP.NET Core 3.1 has become quite clever in figuring everything out, such as identifying that you are using GUIDs for identity. You don’t even need to specify the ApplicationDbContext type, ApplicationUser type, and Role type in your Startup; when you mention these classes, it just looks them up via reflection and figures out the details by itself.

Upvotes: 2

Related Questions