I'm using Entity Framework 6
and the repository pattern, with a service layer on top. In my POCO entity classes, I do use DataAnnotations
for basic requirements such as KeyAttribute
and RequiredAttribute
. I perform business-specific validation in my service layer, though. So for example, my AccountService
has an Insert
method for inserting a new Account
. I'll do checks like whether or not an account is eligible to be created based on some business rules, etc. If it's not eligible then I'll throw a validation exception there.
A problem that I'm trying to solve is what about when an existing Account
is being updated? Where would I perform validation for changes to individual properties of Account
? In my repository pattern implementation, I have a unit of work object which contains the DbContext
and the unit of work class only exposes my individual services (which use that DbContext
) as well as a single SaveChanges
method, which just calls the DbContext
's SaveChanges
method. So, to update an existing Account
, you would fetch it using the service layer, it'd be tracked by the DbContext
and you'd edit the needed properties and call SaveChanges
. There is no Edit
method on my service that forces the user of my library to pass through that for validation.
Where should I perform this kind of validation?
Edit: I'd also be open to a way to make it so that some kind of Edit
method is required, and that fetching existing entities does not track whem in the DbContext
. I think this might complicate things such as lazy loading and stuff, though.