簡體   English   中英

如何使用 SQLite 處理 ASP.NET Core 表單中的唯一索引

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

我是 ASP.NET Core 的新手,我正在創建一個項目,我需要一個數據庫來將用戶存儲在其中。

當我在我的上下文中構建數據庫時,我在我的用戶名 ( Nom ) 和電子郵件 ( Mail ) 字段上放置了一個唯一索引:

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");
}

這是Utilisateur類:

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; }
    }
}

在這一點上,我的字段實際上是唯一的,但是當我輸入非唯一的用戶名或電子郵件時,我收到此錯誤頁面:

在此處輸入圖片說明

有沒有一種方法可以像 ASP.NET Core 那樣使用asp-valifation-for標記為[Required][MinLength(6)]向用戶發送消息?

在此處輸入圖片說明

您可以捕獲異常並將錯誤添加到 ModelState 字典

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;
}

不過,此代碼特定於 SqlLite(因為您的錯誤表明這是您正在使用的數據庫)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM