Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to implement business logic validation - 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

like image 754
Mark Avatar asked Apr 19 '11 13:04

Mark


3 Answers

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.

like image 189
Joe Ratzer Avatar answered Nov 13 '22 16:11

Joe Ratzer


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.

like image 31
Ladislav Mrnka Avatar answered Nov 13 '22 17:11

Ladislav Mrnka


I prefer a version of number 3. I like to abstract Entity Framework anyways using a repository or something similar, in case I want/need to replace EF in the future.

Then for validation/business logic, I use whatever validation techniques make sense for the application, but usually some combination of DataAnnotations (for UI minimum validation) and a validation framework like Fluent Validation for maximum validation/business rules. This validation/business logic lives in both the entity class (DataAnnotations) and in an abstraction layer, which is usually a service layer in my applications.

like image 1
BrandonZeider Avatar answered Nov 13 '22 17:11

BrandonZeider