简体   繁体   中英

How can I handle the Unique index in a form for ASP.NET Core using SQLite

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 :

在此处输入图片说明

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?

在此处输入图片说明

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM