EF 6 - Validate Entity

Validate Entity trong Entity Framework

Bạn có thể xác thực dữ liệu của các thực thể trong Entity Framework. Để thực hiện điều này, ghi đè phương thức ValidateEntity của DbContext như dưới đây.

protected override System.Data.Entity.Validation.DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, System.Collections.Generic.IDictionary<object, object> items)
{
    if (entityEntry.Entity is Student)
    {
        if (entityEntry.CurrentValues.GetValue<string>("StudentName") == "")
        {
            var list = new List<System.Data.Entity.Validation.DbValidationError>();
            list.Add(new System.Data.Entity.Validation.DbValidationError("StudentName", "StudentName is required"));

            return new System.Data.Entity.Validation.DbEntityValidationResult(entityEntry, list);
        }
    }
    return base.ValidateEntity(entityEntry, items);
}

Như bạn có thể thấy trong đoạn mã trên, chúng tôi đang xác thực dữ liệu của thực thể Student. Nếu StudentName trống, thì chúng tôi sẽ thêm DBValidationError vào DBEntityValidationResult. Vì vậy, bất cứ khi nào bạn gọi phương thức DbContext.SaveChanges và cố gắng lưu thực thể Student mà không có dữ liệu cho thuộc tính StudentName, thì nó sẽ ném ngoại lệ DbEntityValidationException. Hãy xem xét ví dụ sau.

try
{
    using (var ctx = new SchoolDBEntities())
    {
        ctx.Students.Add(new Student() { StudentName = "" });
        ctx.Standards.Add(new Standard() { StandardName = "" });

        ctx.SaveChanges();
    }
}
catch (DbEntityValidationException dbEx)
{
    foreach (DbEntityValidationResult entityErr in dbEx.EntityValidationErrors)
    {
        foreach (DbValidationError error in entityErr.ValidationErrors)
        {
            Console.WriteLine("Error Property Name {0} : Error Message: {1}",
                                error.PropertyName, error.ErrorMessage);
        }
    }
}
Lưu ý: phần này chỉ muốn trình bày cho bạn biết về xác thực dữ liệu thực thể trong Entity Framework. Chúng tôi khuyên bạn không nên sử dụng cách này, thay vào đó bạn nên xác thực dữ liệu của thực thể ở tầng presentation trước khi gọi bất kỳ chức năng nào để tương tác với database.