Defining data context and user classes

Once these packages are downloaded, we can create our custom DataContext class that will be derived from the IdentityDbContext class. Usually, with Entity Framework Code First model, we inherit our custom data context class from the DbContext class and then define DbSet properties of entities to create tables. With ASP.NET Core Identity, we have to inherit our custom data context class from the IdentityDbContext class and specify a class that inherits from IdentityUser. IdentityDbContext is the main base class provided by the ASP.NET Core Identity framework that derives from all the necessary classes required to manage roles, claims, users, tokens, and more.

Here is a screenshot of the IdentityDbContext class:

IdentityUser is the wrapper of the DbContext class that is needed by all the custom data context class to define entities. With the IdentityDbContext class, we can still define our custom entities and also get the Identity specific models such as IdentityUser, IdentityRole, and more, and extend them by making relationships using the Fluid API or through attributes amongst entities. We will look at extending entities later in this chapter.

Here is the code of our custom ApplicationDbContext class that derives from the IdentityDbContext base class:

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

}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}

If you notice, we are passing the ApplicationUser class when deriving from the IdentityDbContext class. This is because the IdentityDbContext class is specific to the IdentityUser class provided by the ASP.NET Core Identity framework. However, it's always better to define your custom class, which can be derived from IdentityUser. This way, you can customize your custom user class and add other properties as well to the default user entity. For now, we will just derive it from IdentityUser and specify it in the ApplicationDbContext class defined previously:

    public class ApplicationUser : IdentityUser 
{
public string TwitterHandler { get; set; }
public string LinkedInProfileLink { get; set; }

public string SkypeAccount { get; set; }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.224.226