3

I always see a DbContext.SaveChanges() in the UnitOfWork.Commit() method. But when I fetch an entity from the DbContext and change property, the UnitOfWork.Commit() will write the new entity values back to my database without any validation.

I will avoid to use the integrated DbContext.Configuration.ValidateOnSaveEnabled = true;.

Currently I don't use the UnitOfWork-Pattern. I run the validation on every Insert/Update-operation in my Service classes and if the validation was successful the Repository calls DbContext.SaveChanges().

How to avoid a UnitOfWork.Commit() with invalid entities? If I use the UnitOfWork object in the ASP.NET MVC Controller, as it suggest in this answer: Where does Unit Of Work belong w/ EF4, IoC (Unity), and Repository? ...there is no guarantee that the validation was done.

Community
  • 1
  • 1
rafe
  • 99
  • 1
  • 6

2 Answers2

0

You're basically there. When you're using UoW, your repository updates will be independent of any commits to the data store. Simply move your DbContext.SaveChanges() to a new UnitOfWork.Commit() method (or just use DbContext.SaveChanges() directly as your commit method), and leave the validation logic in your repositories' Insert/Update methods.

using (var uow = new UnitOfWork())
{
  var e1 = new Entity() { ... };
  repo.Insert(e1);  // validates e1 immediately

  var e2 = GetExistingEntity();
  e2.Value = 42;
  repo.Update(e2);  // validates e2 immediately
}
ladenedge
  • 13,197
  • 11
  • 60
  • 117
  • Hi ladenedge, I'm using the DbContext in HttpContext.Items (per Request) so what happens in your example code, when the validation for `rep.Update(e2)` fails? If the entity `e2` from `GetExistingEntity()` is now attached to the DbContext, the changed values will still write back to the database after the Dispose()->Commit() method. Throw an exception in `rep.Update(e2)` would be a possible solution or detach the Entity from the DbContext (my favorite)... – rafe Jul 16 '12 at 18:16
0

I prefer to do not mix validation and data saving. Of course, entities must be validated before saving to database, but this does not means they must be validated on saving.

Depending on application, validation probably will be required outside of context, for example in unit tests, on some UI actions, on remote/client-side validation in ASP.NET MVC and so on, probably not all that actions must cause commiting data.

Maybe it is better to validate all affected entities and than save its? It is easy with default built-in ASP.NET MVC validation because it uses the same attributes as EF. And of course it is even easier if you use third-party validation framework.

REMARK: Also don't forget that some errors can't be handled without saving, it is usually constraints violations and triggers logic. So validation must handle that errors too. Unfortunately I don't know how EF handles that errors, in my development I usually made some hardcoding for each of that constraints.

STO
  • 10,390
  • 8
  • 32
  • 32