1

I'm new to ASP.NET Core and I'm creating a project for which I need a database to store the users inside.

I've put an unique index on my Username (Nom) and E-mail (Mail) fields when I build the database in my context :

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
     modelBuilder.Entity<Utilisateur>().HasIndex(u => u.Nom).IsUnique();
     modelBuilder.Entity<Utilisateur>().HasIndex(u => u.Mail).IsUnique();
     modelBuilder.Entity<Utilisateur>().ToTable("tblUtilisateur");
}

Here is the Utilisateur class:

using System.ComponentModel.DataAnnotations;

namespace Clavardage.Models
{
    public class Utilisateur
    {
        public string Pseudo { get; set; }

        [Required]
        public string Nom { get; set; }

        [Required]
        [MinLength(6)]
        public string Mdp { get; set; }

        [Required]
        public string Mail { get; set; }
    }
}

At this point my fields are actually unique but when I enter a non-unique username or e-mail I get this error page :

enter image description here

Is there a way to just send a message to the user as ASP.NET Core does on it's own for [Required] or [MinLength(6)] with the asp-valifation-for tag?

enter image description here

1 Answer 1

1

You can catch the Exception and Add an Error to ModelState dictionary

try
{
    // Perform database update here
}
catch (DbUpdateException ex)
{
    if (ex.InnerException is SqliteException sqliteException)
    {
        // Parse the error and check that it matches Unique constraint error
        var regex = new Regex("UNIQUE constraint failed: (?<tbl>\\w+)\\.(?<col>\\w+)");
        var match = regex.Match(sqliteException.Message);
        if (match.Success)
        {
            // Get the column name that caused the failure failed 
            var col = match.Groups["col"].Value;
            // Add an error to the ModelState dictionary
            ModelState.AddModelError(col, $"{col} must be unique");
            return View();
        }
    }
    // Another exception happened which we don't know how to handle to we rethrow.
    throw;
}

This code is specific to SqlLite though (since your error showed that this is the database you are using).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, it seems to work. I just don't get what the line return View() is supposed to do. Visual Studio point it as an error and I can't make it work with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.