Entity validation best practices in ASP.NET MVC and ADO.NET Entity Framework

.net asp.net-mvc entity-framework validation


In a project, I'm utilizing ASP.NET MVC and ADO.NET Entity Framework. I want to use partial classes to add validation logic to my entities. It works similarly to how it is shown in the LINQ2SQL-using NerdDinner.com Application for ASP.NET MVC. The primary difference is that, unlike LINQ2SQL, I must utilize the "OnPropertyChanging" event rather than "OnValidating."

The following issues arise from doing it that way: - The "OnPropertyChanging" event is not the best place to invoke validation logic since it always fires, even when using the default constructor to create an object. This has the potential to be quite problematic (not only performance problems). - When determining if an entity has to be validated or not using "EntityState.Detached" (I could discover no other solution) in conjunction with the MVC framework, there are issues. Due to the fact that an entity loses its entity state while being presented in the view (because on POST-event a new entity object is created instead of returning the original one).

Is there a more effective approach to apply validation to ADO.NET Entities? I was unable to locate any tutorials that added validation to ADO.NET Entities in a useful manner.

7/17/2009 8:46:43 AM

Popular Answer

I don't consider the objects themselves to be validators. The xVal library is what I use to perform entity validation.

xVal recommends adding properties that list the different validation rules to your entity classes (or, technically, metadata companion classes). The default validation characteristics that come with.NET in System are these. ComponentModel.DataAnnotations.

After that, you manually do validation on your objects in the business layer. The System is operated utilizing a mechanism for doing this. ComponentModel. Validation logic for DataAnnotations. I created one that reads as follows:

/// <summary>
/// Gets the validation errors for the passed in object by using reflection to retrieve the 
/// <see cref="ValidationAttribute"/>s placed on its properties or on the properties of the object's
/// metadata class (as specified by a <see cref="MetadataTypeAttribute"/> placed on the object's class)
/// </summary>
/// <param name="instance">The object to validate</param>
/// <returns>Any validation errors</returns>
/// <remarks>
/// Borrowed (and cleaned up) from
/// http://goneale.com/2009/03/04/using-metadatatype-attribute-with-aspnet-mvc-xval-validation-framework/
/// </remarks>
public static IEnumerable<ErrorInfo> Validate(object instance)
    //Try to get the MetadataType attribute from the object
    MetadataTypeAttribute metadataAttrib = instance.GetType().GetCustomAttributes(typeof(MetadataTypeAttribute), true).OfType<MetadataTypeAttribute>().FirstOrDefault();

    //If the MetadataType attribute existed, get the metadata class
    //else just use the class of the object
    Type buddyClassOrModelClass = metadataAttrib != null ? metadataAttrib.MetadataClassType : instance.GetType();

    IEnumerable<PropertyDescriptor> buddyClassProperties = TypeDescriptor.GetProperties(buddyClassOrModelClass).Cast<PropertyDescriptor>();
    IEnumerable<PropertyDescriptor> modelClassProperties = TypeDescriptor.GetProperties(instance.GetType()).Cast<PropertyDescriptor>();

    //This query matches each property on the model class against the buddy class
    //gets a list of all invalid validation attributes and returns a list of
    //validation errors
    return from buddyProp in buddyClassProperties
           join modelProp in modelClassProperties on buddyProp.Name equals modelProp.Name
           from attribute in buddyProp.Attributes.OfType<ValidationAttribute>()
           where !attribute.IsValid(modelProp.GetValue(instance))
           select new ErrorInfo(buddyProp.Name, attribute.FormatErrorMessage(String.Empty), instance);

With the help of xVal, you can simply add validation failures to the ModelState in your Controller by throwing a useful exception type that captures them.

By using jQuery, xVal will also automatically produce client-side JavaScript form validation code for you. Provide a HtmlHelper method to validate.

For a tutorial on how it works, see http://blog.codeville.net/2009/01/10/xval-a-validation-framework-for-aspnet-mvc/. It's a pretty beautiful, non-burdensome method of validation, in my opinion. It seamlessly integrates with the ASP.NET MVC methodology.

1/10/2010 4:33:34 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow