I am trying to implement a server side validation for email, where email field will only take unique value and to implement it I used fluent API for unique email which is like this:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Manager>()
.HasIndex(b => b.Email)
.IsUnique();
}
And now whenever I try to enter duplicate email it throws an exception like this:
SqlException: Cannot insert duplicate key row in object 'dbo.Managers' with unique index 'IX_Managers_Email'. The duplicate key value is (test@gmail.com). The statement has been terminated.
How can I stop this and instead letting compiler throw this exception, I make it throw a server side validation or is there another way to do it? Please guide.
Plus adding Manager model as well in case if it is needed
namespace Office.Models
{
[Index (nameof(Email), IsUnique=true)]
public class Manager
{
[Key]
public int Id { get; set; }
[Required]
[DisplayName("Manager Name")]
public string ManagerName { get; set; }
[Required]
[StringLength(450)]
public string Email { get; set; }
[Required]
//[RegularExpression(@"^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$", ErrorMessage = "Password type is not valid include Capital, Small, number and Special Char and length should be Min 8")]
public string Password{ get; set; }
public string Role { get; set; } = "2";
public DateTime JoiningDate { get; private set; }
public Manager()
{
JoiningDate = DateTime.Now;
}
}
}
I tried making Email
unique and expected email to simply not accepting duplicate values and do nothing or throw server side validation, but I got this error
SqlException: Cannot insert duplicate key row in object 'dbo.Managers' with unique index 'IX_Managers_Email'. The duplicate key value is (test@gmail.com). The statement has been terminated.