Reputation: 11
I'm new to Entity Framework, have read Julie Lerman book and lots of articles about it. Have new project that has both database and classes already defined, so have decided to use Code First approach (although it is the new project so database and classes are pretty similar).
So, we have: - database layer with entities, mapping and DbContext - classes (business layer) - WPF with MVVM (UI layer)
If I understand Code First properly, database layer references business layer, UI references both database and business layer. (If I try to add in the business layer reference to database layer, I get circular reference error.)
Basic validation, like required field or length I understand, but where to put additional (more complex) validations if business layer is not aware of database layer?
Thanks, Claire
Upvotes: 0
Views: 1810
Reputation: 364299
Database layer doesn't reference business layer and presentation layer doesn't reference database layer. That would break whole meaning of layered architecture. Correct layering is:
Database Layer -> Busienss Layer -> Presentation Layer
What probably confuse you are entities. In simple architecture entities are shared among all layers. To achieve that you must place them to separate assembly used by all layers.
Validation can take place in any layer:
Upvotes: 2
Reputation: 32447
you can do complex validations in your entity classes by implementing IValidatableObject interface. Then you can do the validations inside
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
//your validation logic. if there are no errors return an empty list
return new System.Collections.Generic.List<ValidationResult>();
}
EF 4.1 is aware of this interface. So it call this method before it saves the changes. If there are any validation errors it will abort the trasnsaction.
Upvotes: 1
Reputation: 13491
Have a look at this blog to get more info about your structure.
That should help.
There are a couple more parts to the blog which are worth working through,
http://weblogs.asp.net/scottgu/archive/2010/08/03/using-ef-code-first-with-an-existing-database.aspx
In general you have options of putting validation in a number of places. Your view models is one place to do it. Throw a ValidationException for instance. If you are using third party controls like telerik then they automatically pick up and display that you have a validation issue.
Upvotes: 0