C# 使用IValidatableObject进行验证

C# 使用IValidatableObject进行验证,c#,validation,linq-to-entities,C#,Validation,Linq To Entities,我将IValidatableObject接口应用于来自数据库的学生类。但是,我不知道如何在Form1端进行此验证。如何验证表单1中的学生类并向用户显示错误消息 public partial class students:IValidatableObject { public int StudentId { get; set; } public short StudentMemberNum { get; set; } public string StudentName {

我将
IValidatableObject
接口应用于来自数据库的学生类。但是,我不知道如何在
Form1
端进行此验证。如何验证
表单1中的学生类并向用户显示错误消息

public partial class students:IValidatableObject
{
    public int StudentId { get; set; }
    public short StudentMemberNum { get; set; }
    public string StudentName { get; set; }
    public string StudentSurname { get; set; }
    public System.DateTime StudentBirthDate { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (string.IsNullOrEmpty(StudentName))
        {
            yield return new ValidationResult("The student's name is required.", new string[] { "StudentName" });
        }
    }
}
public部分班学生:IValidatableObject
{
公共int StudentId{get;set;}
公共短StudentMemberNum{get;set;}
公共字符串StudentName{get;set;}
公共字符串student姓氏{get;set;}
public System.DateTime StudentBirthDate{get;set;}
公共IEnumerable验证(ValidationContext ValidationContext)
{
if(string.IsNullOrEmpty(StudentName))
{
返回新的ValidationResult(“需要学生的名字。”,新字符串[]{“StudentName”});
}
}
}

如果没有来自Form1的代码也很难提供帮助-您正在调用
Validate
Hello there Form protection Validator。我用TryValidateObject()类找到了解决方案。我想知道这样的用途对吗?db.students.Add(学生);var Context=新的ValidationContext(学生);List ErrorList=新列表();bool Error=Validator.TryValidateObject(学生、上下文、HataListesi、true);foreach(ValidationResult在ErrorList中验证){MessageBox.Show(validate.ErrorMessage);}