'How to make autogenerated Guid as ID primary key in ApiAuthorizationDbContext IdentityDbContext instead of string
In ASP.NET Core 6 Web API, I have:
ApplicationUser model class:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string MobileNumber { get; set; }
}
This is the ApplicationUserConfiguration:
public class ApplicationUserConfigurations : IEntityTypeConfiguration<ApplicationUser>
{
public void Configure(EntityTypeBuilder<ApplicationUser> builder)
{
builder.HasIndex(u => u.Email).IsUnique();
builder.HasIndex(u => u.UserName).IsUnique();
builder.Ignore(u => u.AccessFailedCount);
builder.Ignore(u => u.LockoutEnabled);
builder.Ignore(u => u.TwoFactorEnabled);
builder.Ignore(u => u.ConcurrencyStamp);
builder.Ignore(u => u.LockoutEnd);
builder.Ignore(u => u.EmailConfirmed);
builder.Ignore(u => u.TwoFactorEnabled);
builder.Ignore(u => u.AccessFailedCount);
builder.Ignore(u => u.PhoneNumberConfirmed);
}
}
public interface IApplicationDbContext
{
public DbSet<Merchant> merchants { get; set; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
}
I use ApiAuthorizationDbContext. This is the ApplicationDbContext:
public class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser>, IApplicationDbContext
{
private readonly IDateTime _dateTime;
private readonly ICurrentUserService _currentUserService;
private readonly IDomainEventService _domainEventService;
public ApplicationDbContext(
DbContextOptions options,
IOptions<OperationalStoreOptions> operationalStoreOptions,
ICurrentUserService currentUserService,
IDateTime dateTime,
IDomainEventService domainEventService) : base(options, operationalStoreOptions)
{
_dateTime = dateTime;
_domainEventService = domainEventService;
_currentUserService = currentUserService;
}
public DbSet<Merchant> zib_merchants { get; set; }
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
foreach (EntityEntry<AuditableEntity> entry in ChangeTracker.Entries<AuditableEntity>())
{
switch (entry.State)
{
case EntityState.Added:
entry.Entity.CreatedBy = _currentUserService.UserId;
entry.Entity.CreatedAt = _dateTime.Now;
break;
case EntityState.Modified:
entry.Entity.LastModifiedBy = _currentUserService.UserId;
entry.Entity.LastModifiedAt = _dateTime.Now;
break;
}
}
var result = await base.SaveChangesAsync(cancellationToken);
await DispatchEvents();
return result;
}
protected override void OnModelCreating(ModelBuilder builder)
{
ConfigureDecimalPrecision(builder);
builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
base.OnModelCreating(builder);
builder.ApplyConfiguration(new ApplicationUserConfigurations());
builder.ApplyConfiguration(new MerchantConfigurations());
}
}
Program.cs:
public static async Task Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<ApplicationDbContext>();
if (context.Database.IsSqlServer())
{
await context.Database.MigrateAsync();
}
var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
ApplicationDbContextSeed.SeedData(userManager, roleManager);
}
catch (Exception ex)
{
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while migrating or seeding the database.");
throw;
}
}
await host.RunAsync();
}
When I ran the migration, I found that each of the Id of AspNetUsers, AspNetRoles etc are string - nvarchar(450).
How do I make AspNetUsers, AspNetRoles and AspNetUserRoles use autogenerated GUIDs instead?
Thanks
Solution 1:[1]
It seems, you have also "IdentityUser" class. So change Id line to:
[Key]
public Guid Id { get; set; }
and also add the following line in "ApplicationUserConfigurations.cs" and "ApplicationRolesConfigurations.cs".
builder.HasKey(x => x.Id);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Robabeh Ghasemi |
