If you want to use ASP.NET Identity with Entity Framework in your application, you need to add the following dependencies:
"EntityFramework.Commands": "7.0.0-rc1-final", "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final", "Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final",
Create an appsettings.json
file and store the database connection string.
Create a file with the name appsettings.json
at the root level of the project, as shown in the following screenshot:
Store the following connection string in appsettings.json
. This connection string will be used by ASP.NET Identity to store the data in relevant tables:
{ "Data": { "DefaultConnection": { "ConnectionString": "Server=(localdb)\mssqllocaldb;Database=aspnet_security;Trusted_Connection=True;MultipleActiveResultSets=true" } } }
Create a Models folder and a couple of files—ApplicationDbContext.cs and ApplicationUser.cs—as shown in the following screenshot:
The ApplicationUser
class inherits from the IdentityUser
class (available at the AspNet.Identity.EntityFramework6
namespace) as follows:
public class ApplicationUser : IdentityUser { .. }
You can add properties to the user as per the needs of your application. I have not added any properties as I would like to keep things simple to show the features of ASP.NET Identity.
The ApplicationDbContext
class inherits from the IdentityDbContext
class of ApplicationUser
. In the constructor method, we pass the connectionstring
, which is eventually passed to the base class.
Even the OnModelCreating
method is overridden. If you want to change any table names (to be generated by Identity), you can do so as follows:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(string nameOrConnectionString) : base(nameOrConnectionString) { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } }
Once we create the Models
file, we need to configure the application and services. You can configure these in Configure
and ConfigureServices
, which are found in the Startup
class.