Entity Framework Tutorial Basics(40):Validate Entity

本文介绍如何为Entity Framework中的实体自定义服务器端验证。通过重写DBContext的ValidateEntity方法,可以实现对特定实体属性的检查。例如,对于学生实体,如果姓名为空,则会抛出验证异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Validate Entity

You can write custom server side validation for any entity. To accomplish this, override ValidateEntity method of DBContext as shown below.

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);
}

 

As you can see in the above code, we are validating the Student entity. If StudentName is blank, then we are adding DBValidationError into DBEntityValidationResult. So whenever you call DBContext.SaveChanges method and you try to save Student entity without StudentName, then it will throw DbEntityValidationException. For example:

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);
        }
    }
}

 

转载于:https://www.cnblogs.com/purplefox2008/p/5649464.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值