[英]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.我是 ASP.NET Core 的新手,我正在创建一个项目,我需要一个数据库来将用户存储在其中。
I've put an unique index on my Username ( Nom
) and E-mail ( Mail
) fields when I build the database in my context :当我在我的上下文中构建数据库时,我在我的用户名 ( 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");
}
Here is the Utilisateur
class:这是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; }
}
}
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?有没有一种方法可以像 ASP.NET Core 那样使用asp-valifation-for
标记为[Required]
或[MinLength(6)]
向用户发送消息?
You can catch the Exception and Add an Error to ModelState dictionary您可以捕获异常并将错误添加到 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;
}
This code is specific to SqlLite though (since your error showed that this is the database you are using).不过,此代码特定于 SqlLite(因为您的错误表明这是您正在使用的数据库)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.