views:

456

answers:

1

I was wondering what the general recommendation is for Entity Framework in terms of data validation. I am relatively new to EF, but it appears there are two main approaches to data validation.

The first is to create a partial class for the model, and then perform data validations and update a collection of rule violations. This is outlined at http://msdn.microsoft.com/en-us/library/cc716747.aspx

The other is to use data annotations and then have the annotations perform data validation. Scott Guthrie explains this on his blog at http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx.

I was wondering what the benefits are of one over the other. It seems the data annotations would be the preferred mechanism, especially as you move to RIA Services, but I want to ensure I am not missing something. Of course, nothing precludes using both of them together.

Thanks

John

+1  A: 

I have been using DataAnnotations using MVC 2 and it works great. I have not tried the partial on an entity object for validation, but I see its uses. Basically if I create a partial class on an entity object I use it to default data such as a GUID identifier. or Create Date or modified Date. I guess it would be useful to add validations in the partial class perhaps for some complex validation that needs to happen in the entity layer but even then those validations could be accomplished in custom validator. If you are using an MVC website then I would personally use dataannotations.

John Hartsock
What do you think about the issue raised by Brad Wilson here? I guess I am struggling with the Data Annotations since they seem like too much magic :)http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html
John Ptacek
First let me thank you for pointing out this article. It was a good one. This is an informative article about how and why the design change from Input validation was change in MVC1.0 to Model Validation. His points are all valid and should be considered during your design phase. Finally Data Annotations are not magic they are simply property attributes you apply that forces validation code to run when you bind to your model.
John Hartsock
This link explains what I was hoping to do....http://daniel.wertheim.se/2009/11/18/entity-framework-4-part-5-validation-using-dataannotations/Integrate the Data Annotations with a Service Layer. I was having some issues because I am developing for Azure and the 3.5 framework does not support the Validator.TryValidateObject. DOH!Thanks
John Ptacek