Where to specify business rules when using Entity Framework
I'm at a bit of a loss here.
I have a one-to-many relationship between Project and Task and another between Task and TaskEvent.
A Task only exists in the context of a Project and once assigned to a Project can't be changed to belong to another Project.
A business rule states that a Task can only be deleted, and therefore removed from the collection of Tasks that belong to a certain project, if the Task has no TaskEvents captured against it.
How do I specify this in Entity Framework? I'm using Self-Tracking entities, but actually I'm at a loss as to where to define this kind of rule in general. We have other rules that are db ignorant, but how does one define a business rule, preferably that exists in isolation from the entity classes as they are regenerated, as a class of their own with a single responsibility?
I'm thinking I'll have to implement some sort of validator that can use reflection to pick up these 'rule' classes based on the type of the object being validated and then have them each perform their validations.
But how do I push the object context into that? Should my validator have an instance of the object context and then pass it through to each rule as it is execut开发者_如何学运维ed?
And even more flustering, how do I detect the deletes? Will I have to call up the old version of the Project and do a comparison of it's old tasks and current tasks and then check all the deleted ones to make sure they have not TimeEvents captured?
What are the drawbacks to this method and what else can you suggest?
EDIT: I should specify that we're using an n-tier design and both the client apps(MVC and Silverlight) hit WCF services to do anything useful. This is obviously the layer we want to implement the validation in, although if we could use those rules that aren't db specific on the clients that would be great. We're using DataAnnotations for those validations at present.
Thanks
Have a look at this.
Since you are using the n-tier design , my suggestion is to use the EF as a ORM layer rather than a full substitute for domain model. You should create a separate BLL layer that contains business rules and map the domain model to the EF classes. If the mapping is not complicated it can be done manually else you can use tools such as Automapper to perform the mapping for you.
We ended up using a service layer which encapsulated the rules and validated entities based on rule contexts.
For each action there was a context and a set of rules that were associated through the use of an attribute. All associated rules could therefore target the entity of a specific type required by the service action.
The rules were identified using reflection and tested on the service call.
Entity Framework entities still acted as a slightly thinner domain model than I would have liked but we never ran into serious issues and the tracking provided by EF actually helped make some previously impossible rules easy.
精彩评论