Entity Framework 4.1 code first where to validate - entity-framework

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

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:
Presentation layer can validate user input - it can use methods from business layer for that
Business layer should enforce business rules, it can also expose methods for UI to do user input validation
Database layer can validate if entities conform to constraints defined in the database (for example are required columns are filled)

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.

Have a look at this blog to get more info about your structure.
http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx
That should help.
There are a couple more parts to the blog which are worth working through,
http://weblogs.asp.net/scottgu/archive/2010/07/23/entity-framework-4-code-first-custom-database-schema-mapping.aspx
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.

Related

What is Model in MvvM

I have a window with four textbox and one combo. So my Model is like this
Public string FirstName{get;set;}
Public string LastName{get;set;}
Public int Age{get;set;}
Public string Status{get;set;}
It is Right or not
And Model is one to one correspond with elements in User Interface.
I am right or not
The "Model" in MVVM do not describe an object, but a layer. Generally everything that's not presentation (ViewModel layer) or UI (View Layer) falls into the category of Model.
Usually there are two additional layers: Domain/Business Layer and one or more Infrastructure layers (Data Access for example). In the domain layer you have you domain models and (domain) services as well as definitions of repositories (interfaces only).
The repositories gets implemented in the infrastructure layer, so your domain is unaware of their implementation.
Usually you should only pass domain models to your ViewModels, except for maybe simple CRUD operations where you directly display data and edit it, with no business logic enforced on them.
You shouldn't bind your domain or data access models to the View, as it has many side effects (memory leaks in WPF, your views now depend on domain/data access models, it's not refactory safe. Refactory works for classes, but not for properties bound in XAML).
Questions 1: Yes, it is right!
The model is the representation of the data(domain) object you want to deal with.
Questions 2: No, this is not necessarly true.
More important: the model keeps the information and not the behavior attached to it. The User interface usually consists of information and behaviors.

3-Tier Architecture MVC 4 Project

I am working on a Web Application using ASP.Net MVC 4 3-Tier Architecture and I am stuck at certain points. I know here exist similar threads but none were clear enough. I have already created the needed layers which are UI(MVC4 project), BLL- Business Logic Layer(library class), BOL- Business Object Layer(library class that contains ADO.net) and DAL- Data Access Layer (library class).
Layer dependencies are as follows:
UI depends on BOL and BLL
BLL depends on BOL and DAL
DAL depends on BOL
I want you to correct me if I am wrong in the following. The BOL is the master reference layer which exchanges raw dB records with DAL then sends them to BLL which is responsible for any logical computations then gets the updated records and sends them to the controller in the UI.
Knowing the above,
Where should we place the CRUD functions?
Where and why should we create a class for declaring (plus set and get) the useful database fields?
What exactly should we put in the ViewModel folder; in other words since we have already defined the variables in the previous step and in the Entity then does it add any value to keep the Model folder?
Thank you in advance.
Can't be unambiguously correct answers on these issues, so any answer should be evaluated simply as an opinion. Here are my answers:
Where should we place the CRUD functions? CRUD is a frequent pattern at different levels. Hi-level Repository provides similar methods, as a low-level Table Gateway.
Where and why should we create a class for declaring (plus set and get) the useful database fields? These classes are usually simple Data Transfer Objects (DTO) or slightly more complicated Active Records. In accordance with the Dependency Inversion Principle the interface for these classes should provide the Business Logic Layer, and implementation should provide the Data Access Layer. Since DTO is very simple classes, they can be provided "as is" without interface/implementation separation.
What exactly should we put in the ViewModel folder; in other words since we have already defined the variables in the previous step and in the Entity then does it add any value to keep the Model folder? In theory entities should be our models; but in practice it's often not the case. F.e. in ASP.NET MVC models should provide not only the value of drop-down field, but also all possible values; so it requires the separate model class.
The result may be that you have three or four very similar classes at different levels of the application. Of course, it's not very good, so Aspect Programming may be applied in this case.

Is it double work creating a data access component and business component?

I am designing my first Layered Application which consists of a Data, Business, and a Presentation layer.
My business components (e.g, Business.Components.UserComponent) currently has the following method:
public void Create(User entity)
{
using (DataContext ctx = new DataContext())
{
ctx.Users.AddObject(entity);
ctx.SaveChanges();
}
}
I like this design. However, I've encountered some examples online that would recommend the following implementation:
public void Create(User entity)
{
// Instanciate the User Data Access Component
UserDAC dac = new UserDAC();
dac.InsertUser(entity);
}
This would result in creating a Data Access Component for all Entities, each containing the basic methods (Create, Edit, Delete...etc).
This seems like double work since I would have to create the Data Access Components with the basic methods as well as the Business Components that just simply calls the methods in the Data Access Component.
What would be considered best practice for properly implementing the basic CRUD functionalities in a Layered Application? Should they be 'coded' in the Business Component or in a Data Access Component?
It depends. If you expect that your business layer simply do CRUD operations than you can follow your initial approach. If you plan to use some big business logic where business component will work with many entities second approach is better.
Reason why people like to use second approach is testing and persistance ignorance. If you use first approach your business component is tightly coupled with Entity framework. Mocking ObjectContext is not very easy task so testing is hard. If you use second approach your business layer is independent on persistance layer. You can easily test it and you can even change persistance layer if you need to. But those are more advanced concepts which you are probably not looking for at the moment. Your code would need some additional improvement to be testable.
DAC can be also implemented as Repository. There are plenty of ways how to create generic repository so that you have only one class and you define the entity type when instancing repository:
var repository = new GenericRepository<User>();
Also be aware that using separate data access layer introduces new complexity because sometimes it is reasonable to share single context among multiple repositories. This comes together with something known as Unit of work pattern.
There are plenty of articles about implementing Repository and Unit of work patterns on the Internet. I have some of them stored as favorites at home so If you are interested I can include them to my answer later on.

Should i use partial classes as business layer when using entity framework?

I am working on a project using entity framework. Is it okay to use partial classes of the EF generated classes as the business layer. I am begining to think that this is how EF is intended to be used.
I have attempted to use a DTO pattern and soon realized that i am just creating a bunch of mapping classes that is duplicating my effort and also a cause for more maintenance work and an additional layer.
I want to use self-tracking-entities and pass the EF entities to all the layers. Please share your thoughts and ideas. Thanks
I had a look at using partial classes and found that exposing the database model up towards the UI layer would be restrictive.
For a few reasons:
The entity model created includes a deep relational object model which, depending on your schema, would get exposed to the UI layer (say the presenter of MVP or the ViewModel in MVVM).
The Business logic layer typically exposes operations that you can code against. If you see a save method on the BLL and look at the parameters needed to do the save and see a model that require the construction of other entities (cause of the relational nature the entity model) just to do the save, it is not keeping the operation simple.
If you have a bunch of web services then the extra data will need to be sent across for no apparent gain.
You can create more immutable DTO's for your operations parameters rather than encountering side effects cause the same instance was modified in some other part of the application.
If you do TDD and follow YAGNI then you will tend to have a structure specifically designed for the operation you are writing, which would be easier to construct tests against (not requiring to create other objects not realated to the test just because they are on the model). In this case you might have...
public class Order
{ ...
public Guid CustomerID { get; set; }
... }
Instead of using the Entity model generated by the EF which have references exposed...
public class Order
{ ...
public Customer Customer { get; set; }
... }
This way the id of the customer is only needed for an operation that takes an order. Why would you need to construct a Customer (and potentially other objects as well) for an operation that is concerned with taking orders?
If you are worried about the duplication and mapping, then have a look at Automapper
I would not do that, for the following reasons:
You loose the clear distinction between the data layer and the business layer
It makes the business layer more difficult to test
However, if you have some data model specific code, place that is a partial class to avoid it being lost when you regenerate the model.
I think partial class will be a good idea. If the model is regenerated then you will not loose the business logic in the partial classes.
As an alternative you can also look into EF4 Code only so that you don't need to generate your model from the database.
I would use partial classes. There is no such thing as data layer in DDD-ish code. There is a data tier and it resides on SQL Server. The application code should only contain business layer and some mappings which allow persisting business objects in the mentioned data tier.
Entity Framework is you data access code so you shouldn't built your own. In most cases the database schema would be modified because the model have changed, not the opposite.
That being said, I would discourage you to share your entities in all the layers. I value separation of UI and domain layer. I would use DTO to transfer data in and out of the domain. If I have the necessary freedom, I would even use CQRS pattern to get rid of mapping entities to DTO -- I would simply create a second EF data access project meant only for reading data for the UI. It would be built on top of the same database. You read data through read (anemic -- without business logic) model, but you modify it by issuing commands that are executed against real model implemented using EF and partial methods.
Does this answer your question?
I wouldn't do that. Try too keep the layers independent as possible. So a tiny change in your database schema will not affect all your layers.
Entities can be used for data layer but they should not.
If at all, provide interfaces to be used and let your entities implement them (on the partial file) the BL should not know the entities but the interfaces.

Manually written business objects or using DAL objects?

Suppose you have three tiers (with namespaces):
User interface (App.UI) - calls business layer processes and communicates using objects
Business layer (App.Core) - orchestrates processes and uses DAL layer using objects
DAL (App.Data) - directly manipulates store and persists objects
Let's say that you have User table and thus reflected in your DAL layer in App.Data.User and probably also App.Data.Users.
There's a view in your UI that displays application users.
To really have a separated (layered) application, you should also have App.Core.User and App.Core.Users that you'll probably have to create manually.
The best solution (by my opinion) would of course be:
There should be a fourth layer Business Objects (App.Objects) with classes App.Objects.User and App.Objects.Users. These POCOs would be shared among all layers. Business layer would only be allowed to use DAL, UI will only be allowed to use BL, but all of them would use App.Objects for common object model.
Asp.net MVC templates imply on using DAL objects directly on Views, LINQ 2 Entites also don't create any POCOs per se...
So when using any automated code generation are we supposed to use DAL objects or manually hard code our shared POCOs? First part seems as an easy way out but doesn't separate DAL from UI (and may have security and scalability concerns later), the second one is prone to errors and very tedious with medium size database.
What would you suggest?
What you call a App.Objects is basically your Domain Model and it is logical to be shared between all layers to pass the data around but you need to decide if this model will be anemic or active.