I am developing a web app that contains a Blazor front end and a .net WebAPI backend. Both are developed using the .NET 8 version. I also have a class library project where I have all the data related code such as my DbContext Class, all my Data Models and also DTO models etc. My intention with the class library is to reuse the data context and models in multiple front-end apps such as Blazor, MAUI and ASP.NET Core Web App; I have only started with Blazor though. I am also using the .net core Identity framework for authentication and authorization purposes. Maybe it is significant to mention that I am using a MySql database at the backend.
Since I had enabled Authentication with “personal accounts” while creating the Blazor project, it generated quite a few razor pages for the front end along with code to communicate with the database. When I try to test the generated page for password change, it bombs when it tries to update the database. But when I try to do the same or similar things via my WebAPI project using swagger or Postman, it works fine. So, I know the backend code works OK.
Here is the browser error I get
MySqlException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'RETURNING `VersionStamp`;
SELECT `VersionStamp`
FROM `IdentityUsers`
WHERE RO' at line 3
and here is some more stacktrace data from the error:
Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken)
Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore<TUser, TRole, TContext, TKey, TUserClaim, TUserRole, TUserLogin, TUserToken, TRoleClaim>.UpdateAsync(TUser user, CancellationToken cancellationToken)
Microsoft.AspNetCore.Identity.UserManager<TUser>.UpdateUserAsync(TUser user)
Microsoft.AspNetCore.Identity.UserManager<TUser>.ChangePasswordAsync(TUser user, string currentPassword, string newPassword)
ExpenseTracker.BlazorApp.Components.Account.Pages.Manage.ChangePassword.OnValidSubmitAsync() in ChangePassword.razor
+
var changePasswordResult = await UserManager.ChangePasswordAsync(user, Input.OldPassword, Input.NewPassword);
Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
Microsoft.AspNetCore.Components.Forms.EditForm.HandleSubmitAsync()
Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
Though everything works when I use the same DataContext, EntityModel to update the database via the WebAPI works, I will post some of the code here for completeness.
Here is my AddDbContext code from the Program.cs file in the Blazor project:
builder.Services.AddDbContext<ExpenseTrackerDbContext>(options => options.UseMySQL(connectionString));
Here is my DbContext cs file (irrelevant code removed for brevity).
public class ExpenseTrackerDbContext : IdentityDbContext<ETUser, ETRole, Guid, ETUserClaim, ETUserRole, ETUserLogin, ETRoleClaim, ETUserToken>
{
public ExpenseTrackerDbContext()
{
}
public ExpenseTrackerDbContext(DbContextOptions<ExpenseTrackerDbContext> options) : base(options)
{
}
public virtual DbSet<ETUserClaim> ETUserClaims { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
new EntityConfig.ETUserConfig().Configure(builder.Entity<ETUser>());
builder.Entity<ETUser>(entity => { entity.ToTable("IdentityUsers"); });
}
}
Here is my User entity inherited from IdentityUser class:
public partial class ETUser : IdentityUser<Guid>
{
public string Name { get; set; } = null!;
public string? Description { get; set; }
public string CountryCode { get; set; } = null!;
public DateTime? UserCreatedOn { get; set; }
public DateTime? VersionStamp { get; set; }
}
Here is the code for OnModelCreating method of the DbContext class:
public class ETUserConfig : IEntityTypeConfiguration<ETUser>
{
public void Configure(EntityTypeBuilder<ETUser> builder)
{
builder.HasKey(e => e.Id).HasName("PRIMARY");
builder.ToTable("ETUsers");
builder.Property(e => e.Id)
.HasColumnType("binary(16)")
.HasDefaultValueSql("(uuid_to_bin(uuid()))")
.HasConversion<byte[]>();
builder.Property(e => e.Description).HasMaxLength(250);
builder.Property(p => p.CountryCode)
.HasMaxLength(10)
.HasColumnType("VARCHAR(10)");
builder.Property(p => p.UserCreatedOn)
.IsRequired()
.HasDefaultValueSql("CURRENT_TIMESTAMP")
.ValueGeneratedOnAdd()
.HasColumnType("DATETIME");
builder.Property(e => e.VersionStamp).IsRequired()
.ValueGeneratedOnAddOrUpdate()
.HasDefaultValueSql("CURRENT_TIMESTAMP(3)")
.HasColumnType("TIMESTAMP(3)")
.IsConcurrencyToken();
builder.Ignore(e => e.ConcurrencyStamp);
}
}
and finally, this is portion of the code that is generated and included with Identity package for Password change. Since the razor and this code is generated automatically and not modified in any way by me, I am not showing the razor portion. Just the method it calls in response to password change.
private async Task OnValidSubmitAsync()
{
var changePasswordResult = await UserManager.ChangePasswordAsync(user, Input.OldPassword, Input.NewPassword);
if (!changePasswordResult.Succeeded)
{
message = $"Error: {string.Join(",", changePasswordResult.Errors.Select(error => error.Description))}";
return;
}
await SignInManager.RefreshSignInAsync(user);
Logger.LogInformation("User changed their password successfully.");
RedirectManager.RedirectToCurrentPageWithStatus("Your password has been changed", HttpContext);
}
I am pretty certain that the issue is with the way the SQL command is generated by the EF Identity package. Since I don’t have access to the inner most call to update the database, I have no way of what and how the command is generated.
Thanks.
Babu.