C# 将输入到数据库的电子邮件地址与DataAnnotation进行比较

C# 将输入到数据库的电子邮件地址与DataAnnotation进行比较,c#,asp.net-mvc,email,data-annotations,modelstate,C#,Asp.net Mvc,Email,Data Annotations,Modelstate,我的MVC模型中有一个类: public class NewModel { public bool AllComplexes { get; set; } public int UserID { get; set; } public int? RoleID { get; set; } public int ComplexID { get; set; } [Required(ErrorMessage = "Please enter a user name."

我的MVC模型中有一个类:

public class NewModel
{
    public bool AllComplexes { get; set; }
    public int UserID { get; set; }
    public int? RoleID { get; set; }
    public int ComplexID { get; set; }

    [Required(ErrorMessage = "Please enter a user name."), StringLength(50)]
    public string Username { get; set; }

    [Required(ErrorMessage = "Please enter Password"), StringLength(100, ErrorMessage = "Password cannot be longer than 100 characters")]
    public string Password { get; set; }

    [Compare("Password", ErrorMessage = "Passwords do not match")]
    [Required(ErrorMessage = "Please confirm Password")]
    public string RetypePassword { get; set; }

    [RegularExpression( "^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9]+)*\\.([a-z]{2,4})$" , ErrorMessage = "Invalid email format." )]
    [Required(ErrorMessage = "Please enter your e-mail address."), StringLength(50)]
    public string Email { get; set; }

    public List<NEWCategoryModel> Categories { get; set; }
    //public List<NEWPrivilegeModel> userPrivList { get; set; }
    public List<DropDownItem> ComplexList { get; set; }
    public List<DropDownItem> RoleList { get; set; }
    public string NewRole { get; set; }

    public NewModel()
    {

    }
}
我需要使用数据注释将该电子邮件地址与数据库中存储的所有电子邮件地址进行比较。我想我需要一个自定义数据注释?但是我不知道怎么做

这是从数据库获取所有电子邮件地址的查询示例:

  db.ContactInformations.Where(x => x.EMail != null).Select(x => x.EMail);
可以帮助您创建自定义验证。然后,要通过电子邮件检查数据库中是否已存在用户,请尝试:

bool exist = db.UserTable.Any(e => e.Email.ToLower() == emailValue.ToLower());
在中,您将发现一个利用的解决方案,它实现了一个定制的DataAnnotation

您独特的电子邮件验证将遵循以下几点:

[Validator(typeof(NewModelValidator))]
class NewModel
{
    //...Model implementation omitted
}

public class NewModelValidator : AbstractValidator<NewModel>
{
    public NewModelValidator()
    {

        RuleFor(x => x.Email).Must(IsUnieuqEmail).WithMessage("Email already exists");
    }

    private bool IsUniqueEmail(string mail)
    {
        var _db = new DataContext();
        if (_db.NewModel.SingleOrDefault(x => x.Email == mail) == null) return true;
        return false;
    }
}
[Validator(typeof(newmodelvidator))]
类新模型
{
//…省略了模型实现
}
公共类NewModelValidator:AbstractValidator
{
公共NewModelValidator()
{
RuleFor(x=>x.Email).Must(IsUnieuqEmail).WithMessage(“电子邮件已存在”);
}
私人bool-IsUniqueEmail(字符串邮件)
{
var_db=new DataContext();
if(_db.NewModel.SingleOrDefault(x=>x.Email==mail)==null)返回true;
返回false;
}
}
公共类新模型
{
[EmailValidation(ErrorMessage=“电子邮件地址已存在”)]
[RegularExpression(“^[a-z0-9\\+-]+(\\.[a-z0-9\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9]+)*\.([a-z]{2,4})$”,ErrorMessage=“无效电子邮件格式”。]
[必需(ErrorMessage=“请输入您的电子邮件地址”),StringLength(50)]
公共字符串电子邮件{get;set;}
{
公共类EmailValidation:ValidationAttribute
{
受保护的重写ValidationResult有效(对象值,ValidationContext ValidationContext)
{
propmetenties db=新的propmetenties();
if(值!=null)
{
var valueAsString=value.ToString();
IEnumerable email=db.ContactInformations.Where(x=>x.email!=null)。选择(x=>x.email);
if(email.Contains(valueAsString))
{
var errorMessage=FormatErrorMessage(validationContext.DisplayName);
返回新的ValidationResult(errorMessage);
}
}
返回ValidationResult.Success;
}
}

我编辑了我的答案,使用该链接,将exist逻辑添加到IsValid方法中。这个
.ToLower()
创建了新字符串并使垃圾收集器参与其中。
[Validator(typeof(NewModelValidator))]
class NewModel
{
    //...Model implementation omitted
}

public class NewModelValidator : AbstractValidator<NewModel>
{
    public NewModelValidator()
    {

        RuleFor(x => x.Email).Must(IsUnieuqEmail).WithMessage("Email already exists");
    }

    private bool IsUniqueEmail(string mail)
    {
        var _db = new DataContext();
        if (_db.NewModel.SingleOrDefault(x => x.Email == mail) == null) return true;
        return false;
    }
}
public class NewModel 
{
      [EmailValidation(ErrorMessage = "The Email Address already exists")]
      [RegularExpression( "^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9]+)*\\.([a-z]{2,4})$" , ErrorMessage = "Invalid email format." )]
      [Required(ErrorMessage = "Please enter your e-mail address."), StringLength(50)]
      public string Email { get; set; }
{


public class EmailValidation : ValidationAttribute
{

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        PropmetEntities db = new PropmetEntities();
        if (value != null)
        {
            var valueAsString = value.ToString();
            IEnumerable<string> email = db.ContactInformations.Where(x => x.EMail != null).Select(x => x.EMail);
            if (email.Contains(valueAsString))
            {
                var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                return new ValidationResult(errorMessage);
            }
        }
        return ValidationResult.Success;
    }
}