Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advice on POCO Validation with ASP.NET MVC/Entity Framework

Here's the scenario:

  • ASP.NET MVC2 Web Application
  • Entity Framework 4 (Pure POCO's, Custom Data Context)
  • Repository Pattern
  • Unit of Work Pattern
  • Dependency Injection
  • Service Layer mediating Controller -> Repository

So basically, all the cool stuff. :)

Flow of events for a basic UI operation ("Adding a Post"):

  1. Controller calls Add(Post) method on service layer
  2. Service layer calls Add(T) on repository
  3. Repository calls AddObject(T) on custom data context
  4. Controller calls Commit() on Unit of Work

Now, i'm trying to work out where i can put my validation.

At this stage, i need two types of validation:

  1. Simple, independant POCO validation such as "post must have a title". This seems a natural fit for Data Annotations on the POCO's.
  2. Complex business validation, such as "cannot add a comment to a locked post". This can't be done by Data Annotations.

Now, i have been reading "Programming Entity Framework, Second Edition" by Julie Lerman (which is excellent BTW), and have been looking into hooking into the SavingChanges event in order to perform "last-minute" validation. This would be a nice way to ensure validation always happens whenever i do "something" (add, modify, delete), but it's also a little late IMO (as the items are already in the state manager) - so what can i do if validation fails, remove them?

I could of course make my POCO's implement an interface (say "IValidatable"), and call a method on this interface during this event.

But this seems "too late" for business validation - is this the consensus?

I'm basically looking for guidance here, i'm trying to design a re-usable, intelligent validation scheme for complex business logic, given my above architecture.

Another curve-ball for you - as you know, POCO's with EF mean the POCO's have all the properties on the DB - so i might have a "PostID" property, with get/set accessors (as EF needs to get/set these properties).

But the problem is, "PostID" is an identity column, so how do i protect the field from being explicity set? E.g if i (for some reason) do the following:

var post = service.FindSingle(10);
post.PostId = 10;
unitOfWork.Commit();

This will throw a SqlException. How can i prevent this? I can't "hide" the property (make it private, or even internal) as the POCO's are in a seperate assembly to the Repository.

A note on validation - i'm planning to create custom exceptions (deriving from Exception). So when validation fails, i need to throw these exceptions.

That way, i can code something like this on my controller:

[HttpPost]
public ActionResult AddPost(Post post)
{
   try
   {
      IUnitOfWork uow = new UnitOfWork();
      postService.Add(post);
      uow.Commit();
   }
   catch(InvalidPostOperation ipo)
   {
      // add error to viewmodel
   }
}

Will i have to manually do validation on the service layer everytime i do an Add? Then how can i handle Save? (as this is on the Unit of Work, not the service layer).

So to prevent this from being a "all over the place" question, here are my questions:

  1. Simple POCO validation - should this be done with Data Annotations? Pros/cons/gotchas?
  2. Under what circumstances (if any) should we be hooking into the SavingChanges event of the EF Data Context in order to provide validation?
  3. Where should i be performing complex business validation? In the service explicity, or a method on the POCO's (which i can call from service). How can i create an intelligent/reusable scheme?
  4. How can we "hide" auto-generated properties of POCO's from being tampering with?

Any thoughts would be most appreciated.

Apologize if this post is "too long", but it's an important issue and one that can be solved in many ways, so i wanted to provide all the info in order for the best possible answer.

Thanks.

EDIT

The below answer is helpful, but i'm still (ideally) looking for more thoughts. Anyone else?

like image 816
RPM1984 Avatar asked Oct 07 '10 01:10

RPM1984


Video Answer


1 Answers

  1. Well like you said, DataAnnotations is not appropriate for all situations. Cons are mainly complex validation (multiple property and multiple property different object) in my experience.
  2. If i were you, i would leave business/domain validation out of the Data Layer (EF) as much as possible. If there is a Data Layer validation scenario, then fine (eg. validating complex parent/child relationships - this is purely DB stuff).
  3. Yes, the complex business validation should be in the Service Layer or in the Model Objects (attached, via partial classes or some inheritance approach: interfaces/derived classes). There's debate about this between ActiveRecord people, Repository Pattern people and DDD people, but go with what works for you, is simple and will enable rapid deployment and low cost application maintenance. This is a simple example of how you might attach more complex validation to domain objects yet is still compatible with the DataAnnotations interface and thus is 'MVC friendly'.
  4. Good question. -one i have not found a solution i'm 100% happy with yet. I have played with the idea of private setters and it's not great. Have a quick read of this summarized Evans DDD book. It's great quick read and it might provide some insight about the purpose and difference between Model Objects and Value Objects. This is where i think object design will mitigate the problems your having with the property "tampering" (as you call it) but without fixing the property visibility. Ie, another solution might lie elsewhere. Hope this helps.
like image 148
Matt Kocaj Avatar answered Sep 22 '22 03:09

Matt Kocaj