Databases Reference
In-Depth Information
}
private abstract class Metadata
{
[Required]
public object ProductName { get; set; }
[ Required ]
public object UnitPrice { get; set; }
}
}
The following is pseudo-code from the imaginary import application, which creates a new
Product entity in the Northwind database. This code actually compiles and runs without
error; however, in a real application, the product name would not be hard-coded but
loaded form an import file instead:
using (NorthwindEntities context = new NorthwindEntities())
{
var product = new Product();
product.ProductName = “Test Product”;
product.UnitPrice = null;
context.Products.AddObject(product);
context.SaveChanges();
}
Because this code does not validate the new Product instance explicitly, the
RequiredAttribute , newly added to the UnitPrice property, will have no effect, and an
invalid product record will be created in the database without the unit price. Although
you could fix the problem in this particular case, having to call the static ValidateObject
method every time you create or modify an entity instance is repetitive and prone to
errors.
In most scenarios, it is logical to assume that when a developer saves entities to the data-
base, he wants them to be valid, so having to validate them explicitly simply increases the
volume of code without adding any new logic to it. Based on this assumption, you can
override the SaveChanges method of the Entity Framework's ObjectContext to perform
validation for all entities before they are submitted to the database. Listing 8.1 shows how
this can be done.
LISTING 8.1 Overriding SaveChanges Method to Implement Validation
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.Objects;
using System.Linq;
 
Search WWH ::




Custom Search