Based on the answers mentioned here, I understood that I should put the business logic inside the model itself, while in my program I am using EF directly inside the actions of the controller for example to get the list of cars from the database directly I am doing the following:
public ActionResult CarList()
{
using(var _db = new CarRentEntities())
{
var result = _db.Cars.Where(m=>m.Active);
return View(result);
}
}
what is the impact on my website performance if I will use the mentioned above code inside controller or inside Model?
which method I should use? for example if I want to work with a team, is there a standard I should follow to separate the code, kindly advise
for using the repository pattern: I read that we should not use if as mentioned for example here , i will copy some of what mentioned:
The single best reason to not use the repository pattern with Entity
Framework? Entity Framework already implements a repository pattern.
DbContext is your UoW (Unit of Work) and each DbSet is the repository.
Implementing another layer on top of this is not only redundant, but
makes maintenance harder.
if my database contains the following tables: Manufacturers , Cars , Rent , Clients , rent class is the a table with 2 foreign keys between Clients and Cars and contains other detailed fields.
how to deal with Rent Object which need to get data from 2 different repositories Cars and Clients in order to display the renting grid based on search criteria entered by the user, if I will use the repositories Cars and Clients , they have their own dbContext, BOOM my head cannot understand this technique, kindly advise
The answer to your question is, it does not really affect performance but it will definitely become an issue in terms of maintainability as the application grows bigger. You can adopt the SOLID architecture principles: SOLID architecture principles using simple C# examples. This enables you to develop high quality software.
You can create a multi-layered application:
Interface Layer - MVC application
Business Layer - Class Library with classes with logic
Data Access Layer - Database Contexts and Repositories, unit of work with CRUD operations
Shared layer - Logging, AppSettings, validations, utilities, extensions, constants, enums
Having your application in this structure would require you to consider things like inversion of control, dependency injection and many more to ensure loosely coupled classes, easy unit testing and most of all a solid application.
You can also read this: Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application
Generally the Model is a "unit" - i.e. it is a model of the data you want to display. The Controller is an "integrator" - i.e. it pulls together the various resources required to render your web page. You may wish to create a database fascade class which does something like this;
public ActionResult CarList()
{
using(var carStore = new Factory.CreateCarStore())
{
var result = carStore.GetActiveCars();
return View(result);
}
}
To separate your database access from your web controller (this would make it more test-able as well because you can substitute a different CarStore implementation (i.e. a Test XML data set) for testing purposes.
Related
My question is, how do I add a custom query to a model in asp.net mvc , all the tutorial I had seen they make the query in the controller.
So far in my reading everything says that the controller should no be aware of the database, all the queries should be made in the model but I can not seem to find any example of this.
I try to do it but I do not have the DbContext available in the model, so how should I do it?
There are multiple ways to achieve this and each has its own pros and cons. Here are a few appraoches:
1) Domain Model Pattern
The author of the domain model pattern, Martin Fowler, provides this definition (Fowler, 2003):
An object model of the domain that incorporates both behavior and data.
Using this pattern, your domain models would define behaviors, which may or may not translate into DB queries.
2) Repository Pattern
Use a repository to separate the logic that retrieves the data and maps it to the entity model from the business logic that acts on the model. The business logic should be agnostic to the type of data that comprises the data source layer. For example, the data source layer can be a database, a SharePoint list, or a Web service.
As #Mehrdad has pointed out, using this pattern frees up the controller DB concerns and all your DB logic remains in one place.
3) Command Query Separation pattern (my favorite)
It states that every method should either be a command that performs an action, or a query that returns data to the caller, but not both. In other words, asking a question should not change the answer. More formally, methods should return a value only if they are referentially transparent and hence possess no side effects.
Note: this is CQS and NOT CQRS pattern
The difference between CQS and Repository pattern is that with Entity Framework, DbContext already wraps up repository pattern for you (DbContext being the Unit of Work and DbSets being the repositories). So creating another repository layer is redundant. What CQS gives you is fine grained control over your queries/commands and allows you to extend them via decorators which can handle additional logic without polluting your core business logic. Here are some great links about CQS:
Meanwhile... on the command side of my architecture
Returning data from command handlers
Meanwhile... on the query side of my architecture
This answer is a great example of how repository pattern can get be used with CQS together.
All of this can be quite overwhelming, so I suggest that you take your time, implement Proof-OF-Concept projects using these patterns and decide which one suits your overall architecture better.
You usually can use Repository pattern for that for example if you have an user entity:
public class UserRepository:IUserRepository{
public List<User> GetUsers()
{
//Your code and query here
}
public void AddUser(User user)
{
//Your code and query here
}
}
Then you pass this class to your UserController and call it's functions. As you can see I also added IUserRepository so you can use it if you do Dependency Injection
I hope this hasn't been answered already, but I don't even know what to search for.
I have an MVC project, and I need to return a list of users from the DB. Simple enough. But I only want to return certain users. Again, simple stuff.
What has me confused is that I don't know where I should put the code for that. If I put it in the controller I end up with the same code in multiple methods, and spread over multiple controllers.
I've currently put the method to return the users in my dbcontext class. That works and seems to make sense, but I wonder if there's a better way to do it? That class would end up getting massive in a bigger project.
I've looked at using repository classes, but that just seems to be adding an additional layer. I'm using EF6, and not doing any unit testing (yet)
The code below shows the structure of my dbcontext class (I've edited out the actual code, to keep it brief).
public class LeadsDB :DbContext
{
public LeadsDB()
: base("Leads")
{
}
public DbSet<User> Users { get; set; }
public IEnumerable<SelectListItem> GetUserList(bool includeBlank = true)
{
return UserList;
}
}
As they say:
All problems in computer science can be solved by another level of indirection... Except for the problem of too many layers of indirection.
So depending on the size and scope of your app, you need to decide how many layers of indirection will let you hit the sweet spot of maintainability for your application.
If your application is going to be really small, go ahead and put those methods on your context directly. If it's going to be big enough for your DbContext to become unmaintainable, I'd create repositories. And so forth.
In the application I'm working on, we only interact with Entity Framework for data-related operations. All of our repositories return DTOs which are abstractions of our data model. Our Controllers further convert most of our DTOs into ViewModels before passing them to the Views. And there's a "Manager" layer between the controllers and the repositories to handle business logic and security-checking. We end up with a lot of layers, but we've found value in decoupling the view, presentation, business, security, and data models.
This looks like an Entity Framework DBContext; if so, then use this as your Data Layer.
Possibly consider using a "Business Layer" abstraction model to do additional things to your objects. Your data access layer should do just that: work with data.
If you have, say, a singleton class as your business layer, then you could use your data layer to directly work with the data, and then the business layer to apply business logic to that data and return it to your presentation layer (be it a website, a windows form, etc.)
The business logic layer could possibly check for the data in cache and if it doesn't exist, then retrieve it from your data layer, put it in cache and return it to your presentation layer.
I'm working on a project with a system that holds data and I'm thinking about using a data access approach to get data to hand it off to my components on the presentation side of things. I'm thinking of this as an N-tier architecture. Here's my thought:
Presentation layer (WebForms and User Controls)
\/
Data access layer (this is where my question is)
\/
Business objects (a C# class for each entity in the system)
\/
Existing APIs to get data from database (MS SQL-driven)
In my DAL, I want to use a particular API mechanism from the system to get the business objects so I can pass them to my presentation components. I am aware of the repository pattern where I create various utility repository classes to "get a bunch of the X business objects". E.g. say I have a business object called Article, I could have an ArticleRepository and my "Article listing page" would call that repository and get me a collection of Article. This is nice, but might be overkill at the DAL for me. Is there a name of doing something else like just having a static GetAll() method on my business object? So isntead of:
var repo = new ArticleRepository();
IEnumerable<Article> articles = repo.GetAll();
I'm thinking something simple like this:
IEnumerable<Article> articles = Article.GetAll();
Where the Article class is both my business object with relevant properties and even helper methods, but also has a static GetAll() method. Is there a name for this approach? Is it a bad idea to create this slimmed down pseudo-repository?
I ask all this because simply put, I will have LOTS of repository classes to do this because I have lots of business objects, all with unique queries to get them from the system.
Don't know about the name of your architecture, but IMHO DAL should take care of persistence thus dealing directly with DB API.
From my experience, there's no excuse for thinking that some good practice is overkill :)
Generic repository with EF is pretty simple to implement and will make you smile in the future.
Please help on choosing the right way to use the entities in n-tier web application.
At the present moment I have the following assembleis in it:
The Model (Custom entities) describes the fields of the classes that the application use.
The Validation is validating the data integrity from UI using the reflection attributes method (checks data in all layers).
The BusinessLogicLayer is a business facade for additional logic and caching that use abstract data providers from DataAccessLayer.
The DataAccessLayer overrides the abstarct data providers using LinqtoSql data context and Linq queries. And here is the point that makes me feel i go wrong...
My DataLayer right before it sends data to the business layer, maps (converts) the data retrieved from DB to the Model classes (Custom entities) using the mappers. It looks like this:
internal static model.City ToModel(this City city)
{
if (city == null)
{
return null;
}
return new model.City
{
Id = city.CountryId,
CountryId = city.CountryId,
AddedDate = city.AddedDate,
AddedBy = city.AddedBy,
Title = city.Title
};
}
So the mapper maps data object to the describing model. Is that right and common way to work with entities or do I have to use the data object as entities (to gain a time)? Am I clear enough?
You could use your data entities in your project if they are POCOs. Otherwise I would create separate models as you have done. But do keep them in a separate assembly (not in the DataAccess project)
But I would not expose them through a webservice.
Other suggestions
imho people overuse layers. Most applications do not need a lot of layers. My current client had a architecture like yours for all their applications. The problem was that only the data access layer and the presentation layer had logic in them, all other layers just took data from the lower layer, transformed it, and sent it to the layer above.
The first thing I did was to tell them to scrap all layers and instead use something like this (requires a IoC container):
Core (Contains business rules and dataaccess through an orm)
Specification (Seperated interface pattern. Contains service interfaces and models)
User interface (might be a webservice, winforms, webapp)
That works for most application. If you find that Core grows and becomes too large too handle you can split it up without affecting any of the user interfaces.
You are already using an ORM and have you thought about using a validation block (FluentValidation or DataAnnotations) for validation? Makes it easy to validate your models in all layers.
It may be a common practice to send out DTOs from serivce boundary (WCF service, etc.) but if you are directly using your "entities" in your presentation model, I don't see any benefit in doing that.
As to the code snippet you have provided, why not use AutoMappter? It helps by eliminating writing of boiler-plate mapping codes and does that for you if you have a set of convention in place.
Get rid of the model now, before removing it later will require refactoring the whole application. The last project i worked on used this architecture and maintaining the DTO layer and mappings to the database model layer is a huge pain in the arse and offers no usefull benefits. One of the main things that is anoying is that LinkToSql does not effectively support a disconnected data model. You cannot update a database table by creating a new DB entity with a primary key matching an existing record and then stick it into the data context. You have to first retrieve the entity from the database, update it then commit the changes. Managing this results in really nasty update methods to map all the properties from your DTOs to your LinqtoSql classes. It also breaks the whole deferred execution model of LinqToSql. Don't even get me started on the problems it causes with properties on parent classes that are collections of child DTOs (e.g. a customer DTO with an Orders property that contains a collection of order DTOs), managing those mappings is really really fiddly, i had to do some extensive optimisations because retrieving a few hundred records ended up causing LinqToSql to make 200,000 database calls (admittedly there was also some pretty dumbass code as well but you get the picture).
The only valid reason to use DTOs is if you want to have multiple pluggable Data Access Layers e.g. LinqToSql and NHibernate for supporting different DB servers. That way you can swap out the data access later without having to change any other layers. If you don't need to do this then save yourself a world of pain and just use the LinqToSql entities.
I recently began reading Pro ASP.NET MVC Framework.
The author talks about creating repositories, and using interfaces to set up quick automated tests, which sounds awesome.
But it carries the problem of having to declare yourself all the fields for each table in the database twice: once in the actual database, and once in the C# code, instead of auto-generating the C# data access classes with an ORM.
I do understand that this is a great practice, and enables TDD which also looks awesome. But my question is:
Isn't there any workaround having to declare fields twice: both in the database and the C# code? Can't I use something that auto-generates the C# code but still allows me to do TDD without having to manually create all the business logic in C# and creating a repository (and a fake one too) for each table?
I understand what you mean: most of the POCO classes that you're declaring to have retrieved by repositories look a whole lot like the classes that get auto-generated by your ORM framework. It is tempting, therefore, to reuse those data-access classes as if they were business objects.
But in my experience, it is rare for the data I need in a piece of business logic to be exactly like the data-access classes. Usually I either need some specific subset of data from a data object, or some combination of data produced by joining a few data objects together. If I'm willing to spend another two minutes actually constructing the POCO that I have in mind, and creating an interface to represent the repository methods I plan to use, I find that the code ends up being much easier to refactor when I need to change business logic.
If you use Entity Framework 4, you can generate POCO object automatically from the database. ( Link)
Then you can implement a generic IRepository and its generic SqlRepository, this will allow you to have a repository for all your objects. This is explained here : http://msdn.microsoft.com/en-us/ff714955.aspx
This is a clean way to achieve what you want: you only declare your object once in your database, generate them automatically, and can easily access them with your repository (in addition you can do IoC and unit test :) )
I recommend you to read the second edition of this book which is pure gold and updated with the new features introduced in MVC 2
http://www.amazon.com/ASP-NET-Framework-Second-Experts-Voice/dp/1430228865/ref=sr_1_1?s=books&ie=UTF8&qid=1289851862&sr=1-1
And you should also read about the new features introduced in MVC3 which is now in RC (there is a new view engine really useful) http://weblogs.asp.net/scottgu/archive/2010/11/09/announcing-the-asp-net-mvc-3-release-candidate.aspx
You are not declaring the business logic twice. It's just that this business logic is abstracted behind an interface and in the implementation of this interface you can do whatever you want : hit the database, read from the filesystem, aggregate information from web addresses, ... This interface allows weaker coupling between the controller and the implementation of the repository and among other simplifies TDD. Think of it as a contract between the controller and the business.