Database Reference
In-Depth Information
12-2. Validating Property Changes
Problem
You want to validate a value being assigned to a property.
Solution
Let's say that you have a model with a User entity. The User entity has properties for the full name and user name for
the user. You have a business rule that says that each user must have a UserName greater than five characters long.
You want to enforce this business rule with code that sets the IsActive property to false if the UserName is set to a
string less than or equal to five characters; otherwise the IsActive flag is set to true . This approach does not work in a
Code-First approach. The model is shown in Figure 12-2 .
Figure 12-2. The User entity in our model
To enforce our business rule, we need to implement the partial methods OnUserNameChanging() and
OnUserNameChanged() .These methods are called during the property change activity and after the property has been
changed. The code in Listing 12-2 demonstrates one solution.
Listing 12-2. Monitoring the Changing of the UserName Property
class Program
{
static void Main(string[] args)
{
RunExample();
}
static void RunExample()
{
using (var context = new EFRecipesEntities())
{
var user1 = new User { FullName = "Robert Meyers",
UserName = "RM" };
var user2 = new User { FullName = "Karen Kelley",
UserName = "KKelley" };
context.Users.AddObject(user1);
context.Users.AddObject(user2);
 
Search WWH ::




Custom Search