Implementarr Asp.net core Identity 2.1 in a databasefirst project with two contexts

Asked

Viewed 123 times

0

I am encountering a problem. Below I have performed the following steps:

1) I created an Asp.net core web Aplication MVC project without authentication (Asp.net core 2.2).

2) Because I already have a database, I used the Databasefirst schema, so a context was created automatically.

3) I then decided to add Asp.Net Core Identity to my project.

The problem is that I now have two Contexts, one for Identity and the other for my database. Only the database is unique, so I understand that there should be no two contexts.

How do I configure the two contexts in Statup.Cs with the same connection string?

Hugs

1 answer

1

You can inherit Identitydbcontext from the main application context, example:

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

    public DbSet<MessageUser> Message { get; set; }

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

        builder.ApplyConfiguration(new ApplicationUserEntityTypeConfiguration());
        builder.ApplyConfiguration(new MessageUserEntityTypeConfiguration());
        // 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);
    }
}

In this case I have customized Identityuser using the Applicationuser class, but this is optional.

  public class ApplicationUser: IdentityUser
{
    public string CPF { get; set; }

}

Reference: https://docs.microsoft.com/pt-br/aspnet/core/security/authentication/customize-identity-model?view=aspnetcore-2.2

  • Hello, Rafael! Thank you so much for your feedback. If it’s no bother, you could give me a tip on how and where to create this Applicationuser class?

  • Hello Hugo, the Applicationuser class is just an example, you can create the class with the name you want, the important thing here is to inherit Identityuser and in Startup reference it so that EF Core can map it. This you do in services.Addidentity<Applicationuser>() and also in Identitydbcontext<Applicationuser> as per my reply. I added an example link.

  • Good night, Rafael! I will study with affection these tips that Oce passed me and see if I can advance in the project. Thank you again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.