Entity Framework:使用OnChanging()方法验证数据

Entity Framework使我们的编程更加容易。比如,它集成了数据验证方法,使我们可以轻松地实现数据验证。当一个类通过EF和数据库映射时,EF为该类中的每一个类成员都提供了一个"On..Changing"局部方法。通过实现这个局部方法,就可以实现数据验证。

例如,一个名字为"MyClass"的类,对应的数据库表有"MyField"字段:

    public partial class MyClass{...}

EF 自动产生局部类如下:

    public partial class MyClass : global::System.Data.Objects.DataClasses.EntityObject

    {

        public string MyField;

        ...

    }

在这个类当中,有如下定义:

        partial void OnMyFieldChanging(string value);

这个局部方法OnMyFieldChanging() 没有代码实现。到这里,你可能也会猜出来,这个局部方法就是我们谈论的关键。利用它实现数据验证,在你自己定义的局部类中实现这个局部函数,例如:

public partial class MyClass
    {

        ...
        private partial void OnMyFieldChanging(string value)
        {
            if (!string.IsNullOrEmpty(value.Trim()))
                throw new Exception("MyField cannot be blank.");
        }
    }

Entity Framework makes daily life easier. For data validation, EF has a easy way for us. When we have a class that maps to database via EF, EF generates a  partial class which descendents from EntityObject for the class. Within the EntityObject class, for every property, there is a partial method with a name combined with the property name and "On..Changing". This partial method is for you to do your validation.

For example, you have a class with name of "MyClass". It maps to a table with a field with name of "MyField".

    public partial class MyClass{...}

EF generates:

    public partial class MyClass : global::System.Data.Objects.DataClasses.EntityObject

    {

        public string MyField;

        ...

    }

In this class, you will see this:

        partial void OnMyFieldChanging(string value);

This OnMyFieldChanging() method is a partial method and is not implemented.

To here, you may have guessed what I am going to tell you: use this method to do the validation.

For example:

    public partial class MyClass
    {

        ...
        private partial void OnMyFieldChanging(string value)
        {
            if (!string.IsNullOrEmpty(value.Trim()))
                throw new Exception("MyField cannot be blank.");
        }
    }

原文地址:https://www.cnblogs.com/sungang3225/p/3644392.html