I'm Using MVC 3 and I'm having trouble using Entity Framework so I'm trying to understand what would be the best approach to implement my own DAL.
I manage several main entities in my system: User, Department, Calendar etc...
I'm trying to understand the best practice using this kind of tiered architecture.
Should the DAL implement methods that only return DataTables or DataSets or should it be familiar with the model\ business object (User, Department Calendar etc..)?
Should it hold the classes representing the different models\ business object ?
Where should I place the different repository classes are they part of the DAL as well?
1) Should the DAL implement methods that only return DataTables or DataSets
Absolutely not. DataTables and DataSets are artifacts of the past. DAL methods should take/return your DAL entities. For example if you are using Entity Framework those would be the autogenerated classes that EF created for you. Or if you are using EF Code First those would be the classes you wrote to map to your SQL tables
2) Should it hold the classes representing the different models\ business object ?
As explained in 1) the DAL layer should contain the entities that are mapped to your SQL tables as well as the implementation of the repository interface. The repository interface defines the operations with those entities. Inside the DAL layer you will implement this interface for Entity Framework (if this is what you intend to use). Inside the methods you will use the DataContext to perform the different operations with your entities.
3) Where should I place the different repository classes are they part of the DAL as well?
You should place them in the same assembly as your data access classes.
The ASP.NET MVC application will then consume the DAL layer. Your Controllers will simply take the repository interface as constructor parameter and inside the actions you will call various methods on it. You will then configure the Dependency Injection framework of your choice to inject the specific implementation of this repository interface into the controller. This implementation will be the one specific to Entity Framework.
But no matter what you do, don't forget to define view models inside the ASp.NET MVC application itself. Those could be placed inside the Models folder. The view models are the classes that you will be passing to your views. A typical controller action will use the repository to fetch one or more domain entities, map those entities to a single view model that you have defined for the particular view and finally pass the view model to the view. Of course this works the other way around: a controller action takes a view model as action parameter from a view, maps this view model to one or more domain entities and calls one or more methods from the repository passing those domain entities to them.
Related
I have created a solution with 4 Layers (4 projects):
Entity Framework Layer (EFL)
Data Access Layer (DAL): all of queries and CRUD operations
Business Logic Layer(BLL): my business terms and calling DAL classes
MVC Layer (MVCL)
I added reference of EFL to all layers and added DAL reference to BLL and reference of BLL to MVCL layer.
My problem is my entity classes that are in EFL layer. I can add a reference of EFL in MVCL and use these classes in controllers and views but what about MVC model if I do that?
I create all the EFL classes in model folder of MVC but I didn’t use MVC model.
I just used EFL class. Is it true? Or maybe I should create some function to convert EFL and MVC model classes to each other and then I just use MVC model classes?
Which architecture is true here?
My problem is my entity classes that are in EFL layer. I can add a reference of EFL in MVCL and use these classes in controllers and views but what about MVC model if I do that?
Create a common library (new project). This project should contain your interfaces and common entity classes (like the models used in EF). This project should have 0 dependencies on your other projects, your other projects can then reference this project. This will you to reuse your entity objects across your layers (if needed) and also allow you to define common interfaces on your services so you can expose those from your layers instead of your concrete implementations.
I just used EFL class. Is it true? Or maybe I should create some function to convert EFL and MVC model classes to each other and then I just use MVC model classes?
Whether or not to use a EF model across your layers and into your top presentation layer depends on the model and how it is used. Some times this is fine especially with very simple models or in a simple project. Other times it is not and you will want to convert the model to something that more closely mirrors how the end actor will be manipulating it (including validation and possible dependencies). It usually situation specific unless you specify some common standard across your solution.
I'm new to ASP.Net MVC and I'm having a question I can't seem to find the answer to on the Googles.
I have a page that needs a model that is significantly different from the way the data is stored in the database. It's trivial for me to write a function that would translate from the database model to the required MVC model (MyModel ConvertToMvcModel(DataFromDatabase d).
My question, where should I put this code? Should it be in the controler. Should it be in the Data access layer (Using the repository pattern).
Another related question is where should I put the repository class? Up until now I've put repository classes allong side the model class in the same .cs file since every model had a corresponding repository. This time the model will be different from what I get from the repository so it does not make much sense to put it in the same file. Maybe I should separate all my DAL (repositories) from the model code.
Any suggestions?
My question, where should I put this code?
The mapping between your domain models and view models should ideally be placed inside a separate and dedicated mapping layer. For example if you use AutoMapper, which I would recommend, you could place your mapping definitions inside separate files called profiles and inside the controller action simply call the Mapper.Map<TSource, TDest> method.
Another related question is where should I put the repository class?
Up until now I've put repository classes allong side the model class
in the same .cs file since every model had a corresponding repository.
The DAL represents the data access layer and is where the repositories should go. You could define a common contract (interface) that the repositories must obey (implement) and then have several implementations against the different data sources that you are working with.
You shouldn't return entities anyway, use ViewModels for that purpose.
Regarding the mapping: what you're looking for already exists, it's called AutoMapper. You can let the service layer return entities to your controller, and the controller will map them to ViewModel objects.
Keep in mind to initialize the mappings only one time, so launch them from your application start.
Firstly, Sorry For lengthy question but I have to give some underlying information.
We are creating an Application which uses ASP.net MVC, JQuery Templates, Entity Framework, WCF and we used POCO as our domain layer. In our application, there is a WCF Services Layer to exchange data with ASP.net MVC application and it uses Data Transfer Objects (DTOs) from WCF to MVC.
Furthermore, the application uses Lazy Loading in Entity Framework by using AutoMapper when converting Domain-TO-DTOs in our WCF Service Layer.
Our Backend Architecture as follows (WCF Services -> Managers -> Repository -> Entity Framework(POCO))
In our application, we don't use View Models as we don't want another mapping layer for MVC application and we use only DTOs as View Models.
Generally, we have Normal and Lite DTOs for domain such as Customer, CustomerLite, etc (Lite object is having few properties than Normal).
Now we are having some difficulties with DTOs because our DTO structure is becoming more complex and when we think maintainability (with general Hierarchical structure of DTOs) we lose Performance.
For example,
We have Customer View page and our DTO hierarchy as follows
public class CustomerViewDetailsDTO
{
public CustomerLiteDto Customer{get;set;}
public OrderLiteDto Order{get;set;}
public AddressLiteDto Address{get;set;}
}
In this case we don't want some fields of OrderLiteDto for this view. But some other view needs that fields, so in order to facilitates that it we use that structure.
When it comes to Auto Mapping, we map CustomerViewDetailsDTO and we will get additional data (which is not required for particular view) from Lazy Loading (Entity Framework).
My Questions:
Is there any mechanism that we can use for improving performance while considering the maintainability?
Is it possible to use Automapper with more map view based mapping functions for same DTO ?
First of don't use Lazy Loading as probably it will result in Select N+1 problems or similar.
Select N + 1 is a data access anti-pattern where the database is
accessed in a suboptimal way.
In other words, using lazy loading without eager loading collections causes Entity Framework to go to the database and bring the results back one row at a time.
Use jsRender for templates as it's much faster than JQuery Templates:
Render Bemchmark
and here's an nice info for how to use it: Reducing JavaScript Code Using jsRender Templates in HTML5 Applications
Generally, we have Normal and Lite DTOs for domain such as Customer,
CustomerLite, etc (Lite object is having few properties than Normal).
Your normal DTO is probably a ViewModel as ViewModels may or may not map one to one to DTOs, and ViewModels often contain logic pushed back from the view, or help out with pushing data back to the Model on a user's response.
DTOs don't have any behavior and their purpose is to reduce the number of calls between tiers of the application.
Is there any mechanism that we can use for improving performance while considering the maintainability?
Use one ViewModel for one view and you won't have to worry about maintainability. Personally i usually create an abtract class that is a base, and for edit,create or list i inherit that class and add properties that are specific for a view. So for an example Create view doesn't need PropertyId (as someone can hijack your post and post it) so only Edit and List ViewModels have PropertyId property exposed.
Is it possible to use Automapper with more map view based mapping functions for same DTO ?
You can use AutoMapper to define every map, but the question is, how complicated the map will be. Using one ViewModel per view and your maps will be simple to write and maintain. I must point out that it is not recommended to use Automapper in the data access code as:
One downside of AutoMapper is that projection from domain objects
still forces the entire domain object to be queried and loaded.
Source: Autoprojecting LINQ queries
You can use a set of extension that are limited as of now to speed up your mapping in data access code: Stop using AutoMapper in your Data Access Code
Regards
We do like EntityFramework (CTP5) quite a lot and Using it along with ASP.NET MVC3.
What I dislike is;
things are mixed in together.
I can place a DisplayAttribute, RequiredAttribute, RangeAttribute, CompareAttribute together in the same class which means I am mixin in database validation, some business logic and UI alltogether. I can even place ScriptIgnore attribute to customize it as a Json DTO object. So I can use the same POCO class for Persistance, Presentation, DTO and Business Object, and as my domian model.
Which design patterns do you follow along with EF POCO + MVC3 toolset. What layers do you have?
What resposibilities do you add to your classes (Is Your POCO class also your Domain Model)
I use View Models to solve this problem. Validation and UI presentation attributes go to the view model. In this pattern the controller uses a repository to fetch an EF model, maps this EF model to a view model (I use AutoMapper for this) and passes the view model to the view. Because the view model contains all the UI presentation attributes the view behaves as expected. Each view must have its own view model. This means that you could have multiple view models associated to the same EF model but contain a different subset of properties and display formatting attributes based on the specific requirements of the view.
The process works the other way around as well: the controller receives a view model from the view as argument. It maps the view model back to a model and passes the EF model to the repository. UI validation attributes are handled on the view model because you could have different validation requirements in different views: think for example Insert/Update views. In the insert view you will be creating a new entity thus the Id property won't be required. You won't even have an Id property on your view model in this case. In the update view on the contrary the Id property will be required.
My POCO classes are almost always domain models and almost never view models so I don't have these problems.
The best practice is to use special "view model" class when passing data from controller to view (or as JsonResult). In such case you mark UI based attributes in that view model. In most cases (except pure crud applications) you need to display something more or something less then your domain object so you still need some view model (unless you use ViewData directly).
Data annotations on domain object makes sense only if you want to use them for business/data level validation which can take different rules then UI validation.
If you want to follow strict DDD where POCO classes are domain objects = offers methods performing domain logic on instance of object you should go even further because in such case your business facede should not expose domain objects to controller. In such case you will end up with data transfer objects exposed on business facade and consumed in controller. I'm not purist so in this scenario I'm open minded to using data annotations on DTOs directly but it depends on another requirements.
I'm using NHibernate to persist my domain objects.
To keep things simple I'm using an ASP.NET MVC project as both my presentation layer, and my service layer.
I want to return my domain objects in XML from my controller classes. After reading some posts here on Stack Overflow I gather DTOs are the way to go. However, I've also come across posts talking about the ViewModel.
My question: Are Data Transfer Objects and ViewModels the same thing? Or is a ViewModel a kind of sub pattern of a DTO?
The canonical definition of a DTO is the data shape of an object without any behavior.
ViewModels are the model of the view. ViewModels typically are full or partial data from one or more objects (or DTOs) plus any additional members specific to the view's behavior (methods that can be executed by the view, properties to indicate how toggle view elements etc...). You can look at the viewmodel as all the data for a view plus behaviors. ViewModels may or may not map one to one to business objects or DTOs.
By the way, NHibernate projections come in handy if a certain viewmodel needs a subset of the data from a persisted object.
ViewModel in ASP.NET MVC practice is the same as the DTO, however ViewModel in MVVM pattern is different from DTO because ViewModel in MVVM has behaviors but DTO does not have.
DTO != ViewModel
In the MVVM pattern the ViewModel is used to isolate the Model from the View. To represent the Model you could use simple DTO classes, which again is mapped to a database through e.g. NHibernate. But I've never seen a ViewModel class which is modelled as a DTO.. ViewModel classes mostly have behavior, which DTOs don't have.
DTO - Data Transfer Objects are exactly as it says, containers for transferring data. They have no behaviour but merely a bunch of setters and getters. Some people make them immutable and just create new ones when needed rather than updating existing ones. They should be serializable to allow transfer across the wire.
Generally DTOs are used to ship data from one layer to another layer across process boundries as calls to a remote service can be expensive so all the required data is pushed into a DTO and transferred to the client in one chunk (coarse grained).
However, some people use the notion of screen bound DTOs (nothing to do with crossing process boundries). Again these are populated with the required data (generally the data required for a particular screen and could be an aggregation of data from various sources) and sent to the client.
http://blog.jpboodhoo.com/CommentView,guid,21fe23e7-e42c-48d8-8871-86e65bcc9a50.aspx
In simple cases as has already been stated this DTO can be used for binding to the view but in more complex cases it would require the creation of a ViewModel and unloading of data from DTO to ViewModel which is obviously more work (when applying MVVM pattern).
So again as already stated DTO!=ViewModel
and
DTO and ViewModel have different purposes in life
For some simple views I'll use my DTO as my models, but as Views become more complex I'll create ViewModels.
For me it is a balance between quickness (using DTO, since I already have 'em) and flexibility (creating ViewModels means more separation of concerns).
First, the major difference is that ViewModel can have behaviour or methods that DTO Must Not !!!
Second, Using DTO as a ViewModel in ASP.NET MVC make your application tightly coupled to DTO and that's exactly the opposite purpose of using DTO. If you do so, what's the difference using your domain Model or DTO, more complexity to get an anti-pattern ?
Also ViewModel in ASP.NET can use DataAnnotations for validation.
The same DTO can have different ViewModels Mapping, and One ViewModel can be composed from differents DTO (always with object mapping not composition) . because i think it is even worse if you have a ViewModel that contains a DTO, we will have the same problem.
From your presentation layer, think about DTO as a contract, you will receive an object that you have to consider as stranger to your application and don't have any control on it (even if you have ex the service, the dto and presentation layers are yours).
Finally if you do this clean separation, developpers can work together with ease.
The person who design ViewModels, Views and Controllers don't have to worry about the service layer or the DTO implementation because he will make the mapping when the others developpers finish their implementation...
He can even use Mocking tool or manual mocking to fill the presentation layer with data for test.
If you need to change or enhance the DTO then create a ViewModel. It's also OK for the ViewModel to reference the DTO as a complex property.
In practice, you will generally want to add view-specific properties or methods to the model you are using in the view. In such cases,
never modify the DTO for your view requirements. Instead, create a ViewModel and map from your DTO to the ViewModel.
If you will use DTO as ViewModel, that means you are making high dependency on DTO because of some reason you are changing DTO then it could impact on ViewModel.
Better use DTO & convert into viewmodel.
We can use DTO same as Model class and we can use viewmodel when we needs to show/use multiple models data/property in a single view. Example: I create some model using entity framework database first. So, now all the model generate based on the database. and now we need data annotation, for those data annotation we can create a folder name DTO, In this DTO folder, we can keep all the models exact which already generate and add data annotation above the property. Then we can use any operation(use controller , views) using this DTO classes. And when we need complex view, I mean when we need multiple classes data in one view there we can use viewmodel. For viewmodel we can create a folder name viewmodel, then create a custom class and keep that property which we need. I tried to clear myself. Any suggestion highly appreciated.