views:

88

answers:

1

What's the best way of implementing xVal when using the Entity Framework? I've been using this approach but I'd like to know if there's a better way of doing it.

Also I'd like to know if there's a way of doing it without having to raise an exception.

+1  A: 

The metadata approach works well, but the approach that I've used is to have a separate set of ViewModel objects and use a tool like AutoMapper to map from the EF objects to the ViewModel objects. (In more complex implementations, there is a separate domain model in between the EF objects and ViewModel objects.)

If you implement a repository pattern to retrieve your ViewModel objects, it also makes testing your controllers a lot easier to do.

You can then attribute your ViewModel objects to your heart's content and not worry about codegen overwriting your attributes. It's also possible to use another validation method (e.g. FluentValidation), since these can be made to work smoothly with xVal.

mkedobbs
Is there a way to use fluent for client-side validation?
Raúl Roa
This is the right approach (+1), but projection is a *much* better way to map EF -> View models. http://blogs.teamb.com/craigstuntz/2009/12/31/38500/ AutoMapper means materializing full entities, which means inefficient SQL and requires you to think about eager loading, lazy loading, etc. Projection "just works." Still, +1 for view models.
Craig Stuntz
@craig Yeah, good point and good link. @Raul Yes, you can. There is a FluentValidation to xVal connection in the latest builds of FluentValidation.
mkedobbs