Add DbContext and Create Identity Tables - bondaigames/ASP.NET-Core-Documentation GitHub Wiki

  • Install Microsoft.AspNetCore.Identity.EntityFrameworkCore in Nuget
  • Copy Data folder on Coupon Project to Auth API
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace Services.AuthAPI.Data
{
    public class AppDbContext : IdentityDbContext<IdentityUser>
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
            
        }

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

  • Edit file Program.cs
// Add services to the container.
builder.Services.AddDbContext<AppDbContext>(option =>
{
    option.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
//Add this line to activate the Identity Asp.net Feature
builder.Services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<AppDbContext>()
    .AddDefaultTokenProviders();

app.UseHttpsRedirection();
//Add this line before Authorization
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();
ApplyMigration();
app.Run();

void ApplyMigration()
{
    using (var scope = app.Services.CreateScope())
    {
        var _db = scope.ServiceProvider.GetRequiredService<AppDbContext>();

        if (_db.Database.GetPendingMigrations().Count() > 0)
        {
            _db.Database.Migrate();
        }
    }
}
  • Go to appsettings.json in CouponAPI Project and copy Connection Strings
"ConnectionStrings": {
  "DefaultConnection": "Server=DESKTOP-01;Database=Auth;Trusted_Connection=True;TrustServerCertificate=True;Integrated Security=true"
}
  • Open Package Manager Console
add-migration AddIdentityTables
update-database