Where/when should i validate my data when using EF and POCOs?
I started a project to see what EF 4 can do with POCOs. I created a db and a custom POCO. Now i want to validate my data. For this i'm usin开发者_Go百科g the Enterprise Library Validation Block 5.
I have no problem including the validation in my POCOs through attributes and using it with Entity Framework but this means that my POCOs wouldn't be POCOs anymore because i inserted the dependency to the Validation framework.
Any advice where should i insert the validation part and keep the POCOs clean?
Personally I don't see that much of a problem having validation as part of the entities - after all, the entities are part of your domain model, and validation rules can be thought of, arguably, as part of their attributes. I'm no domain modeling expert though :)
In the end, validation will need to be somewhat coupled with the entities. If you decide to decrease the coupling, I think there's a risk of ending up with awkward code. For my latest project, I did split up the validation into different classes, which were placed in partial classes of the entities, and I'm quite happy with the result so far.
I agree that you would like to keep your entities free from validation. It is not the responsibility (SRP) of the domain object itself.
Besides attribute based validation, the Enterprise Library Validation Application Block (VAB) also supports configuration based validation. There are two models you can follow here:
Use XML based configuration. This is well supported. The VAB contains a configuration tool that allows you to configure the whole thing without writing a single line of XML. Especially the 5.0 tool is very good. Still, using XML makes it hard to refactor anything in your model (however, unit tests will help you spot error sooner).
Using code based configuration. While I personally like this model, because it can do a much better job in making your domain easy to refactor. You can get it to work, but it isn't a well supported yet. You can look at this thread to see an example of how to code based configuration and what the current short comes are.
Good luck.
I would create a service class and do the validation in that class.
For instance, you have a POCO class called Listing. Create a service class called ListingService. Then do the validation in ListingService in a method called ValidateListing.
精彩评论