Home > Mobile >  How to generate error message in EF Core OnModelCreating(ModelBuilder modelBuilder)
How to generate error message in EF Core OnModelCreating(ModelBuilder modelBuilder)

Time:06-25

I'm trying to generate desired error message if Email or UserName are not unique. Using Swagger API, at the moment I just get really big response saying I cant insert duplicate value into a table. I want to replace it with error message like "Username already exists".

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyConfiguration(new UserEntityConfiguration());

    modelBuilder.Entity<User>()
           .HasIndex(u => new { u.Email, u.UserName})
           .IsUnique();
}

CodePudding user response:

There doesn't seem to be a way to change the error message in OnModelCreating. If you accept, you can do the validation in the controller and customize the error message.

You can refer to the following code:

[HttpPost]
public async Task<IActionResult> Test(UserTest userTest)
{
    if (ModelState.IsValid)
    {
         try
         {
              _context.UserTest.Add(userTest);
              _context.SaveChanges();
              return RedirectToAction("Index");
         }
         catch (Exception ex)
         {
              var sqlException = GetInnerException<SqlException>(ex);

              if (sqlException != null
                        && (sqlException.Number == 2627 || sqlException.Number == 2601))
              {
                   ViewData["Message"] = "Username already exists";
                   return View();
              }
         }
    }
    return View();
}

public TException GetInnerException<TException>(Exception exception)
where TException : Exception
{
     Exception innerException = exception;
     while (innerException != null)
     {
         if (innerException is TException result)
         {
             return result;
         }
         innerException = innerException.InnerException;
     }
     return null;
}

Test Result:

enter image description here

  • Related