Entity Framework is the best approach for implementing business logic validation.

c# entity entity-framework


I'm using Entity Framework for the first time, and I need to add business logic before inserting new objects into the db, here are the options I thought about:

  1. Implement business logic on the DataContext level - by overriding SaveChanges method
  2. Implement business logic for each entity using OnPropertyChanging partial method
  3. Wrap the generated code in a custom class that implement the validation layer.

Which method is best practice when managing business logic on Entity Framework

4/19/2011 1:48:07 PM

Accepted Answer

Have a look at validation with EF - the validation is inside the entities themselves.

It's a very clean way to organise your project.

When you have POCOs, the obvious place for entity validation is in the POCO itself.

It makes sense that any validation of the Customer object is actually in the Customer class.

10/31/2016 6:16:01 PM

Popular Answer

My experience:

  1. This works but it is quite lot of work and in case of many entities which must be validated this can be slower. Actually EFv4.1 does this automatically.
  2. I don't like this way - it serves only single property changes and doesn't work for complex validation where you need to modify several properties before you get a valid state.
  3. Perhaps - I like validation on demands. Each entity can expose Validate method which will check that state of the whole entitiy is correct.

But all this works only if you always use the whole entity. Once you start to use partial updates and other features you will still have to handle validation elsewhere. That is another +1 for validation on demand.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow