Adding validations to entity classes

Validating data is the process of confirming that the values entered into data objects comply with the constraints in an object's schema, in addition to the rules established for your application. Validating data before you send updates to the underlying database is a good practice that reduces both errors and the potential number of round trips between an application and the database.

The Object Relational Designer (O/R Designer) provides partial methods that enable users to extend the designer-generated code that runs during Inserts, Updates, and Deletes of complete entities, and also during and after individual column changes.

These validation methods are all partial methods. Therefore, there is no overhead at all if you don't implement them, because unimplemented partial methods are not compiled into IL.

You can implement a validation method in another partial class. In our example, we can add the following method to the existing NorthwindDataContext.cs file:

public partial class Product
{
partial void OnProductNameChanging(string value)
{
if (value.IndexOf("@") >= 0)
throw new Exception("ProductName can not contain @");
}
}

Note that this method should be placed inside the partial class Product, and not inside NorthwindDataContext.

Now, we can test it using the following code:

Product product = (from p in db.Products
where p.ProductID == 5
select p).First();
try
{
product.ProductName = "Name @ this place";
db.SubmitChanges();
}
catch (Exception e)
{
Console.WriteLine("Update failed. Reason: {0}", e.Message);
}

Run this program, and you will get an output as shown in the following image:

Adding validations to entity classes

You can implement any of the validation methods for any properties, before or after the change.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset