Add query to model in asp.net mvc - c#

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

Related

What is the standard I should use in MVC coding

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.

Does adding extension methods to ViewModel Maintain ViewModel Rules?

There are certain methods in my ViewModel that access a database connection. I know this is not correct since the ViewModel shouldn't be responsible for connecting to a database.
So as a solution, I moved some of my methods to another class as extention methods. I.e.
Public static void (this MainViewModel viewModel){
viewModel.Textbox = "hello";
viewModel.Tables = GetDatabaseConnectionAndReturnTables();
//...//
}
Is this really a way to get database connection functionality out of the viewmodel? This is the only solution I could come up with.
Thanks,
Luke
Is this really a way to get database connection functionality out of
the viewmodel?
Short answer: no.
Not that long answer: extension methods are meant to add methods to types when source code isn't available, you can't derive a class or you want to add them to a struct (struct aren't inheritable...).
Actually you're adding methods to your view models as if they were added as direct class members. Either if you implement them as view model instance members or using extension methods, you're implementing methods in the view model.
If you want to effectively abstract data from view models you should check some design patterns like:
Repository.
Unit of Work.
Domain model.
Service layer.
Inversion of control.
DTO.
It would be hard to provide you more guidance about how to achieve a true separation of concerns in a Q&A format (I would need to write a book here), but I would start learning more about these design patterns.
Also, I would take a look at what's domain-driven design.
Going this route could get pretty wacky. If there was a choice between extension methods and nesting the functions within the view-model, then the latter would be preferred.
However... both are pretty bad practice. You should read up on the DAO and Repository design patterns. Using the DAO pattern, you hide the details of the database, only exposing the knowledge of a persistence layer. Then with the Repository pattern you expose methods that allow you to manipulate a particular data-set without any care for how that data is retrieved and/or stored.
Using dependency injection you would then inject the repository into a model that does a specific task with that data. Again, you would then pass that model into your view-model which simply displays the information that is available from the model.
One of the big reasons why you keep your data access out of the view models in MVVM is to help with testing. One of the huge advantages of using MVVM is in making more of your code testable, without taking a dependency on the View. By making your view model call an extension method, you have no way of abstracting out the data store calls. This means that when you do your unit testing, you must always have data in the database, ready to be queried against. It also means your data base will fill up with a bunch of crap data that is inserted when your unit tests are ran. You want to hit your data-base when you are writing integration tests, but not really when you are just testing the functionality of your view models.
Abstracting the data access out in to a service or repository, that is hidden behind an interface allows you to test your code, without having to deal with having a connection to the database. You would create fakes or mocks.
This way, your code would do this:
private IMyRepository repository;
public MainWindowViewModel(IMyRepository repo)
{
this.repository = repo;
}
public Task SaveObject(MyObject obj)
{
return this.repository.Save(obj);
}
When you unit test, you just provide a mock, or fake, to your view model constructor and let it hit the save method on those instead.
Your use of an extension method still means you are tightly coupled to your data-layer. It might be abstracted in to a different file, but your view-model is still tightly coupled due to the fact that you can't swap out the data-access without re-writing the original extension method.
The other benefit of this, is that other view models may use the same methods if they need to ask for data. This saves having to copy & pasting the code into extension methods for each view model that might need it or creating an instance of a view model just to get access to its extension methods to fetch your data. View models are typically limited to one view, but the data they are provided with can be used on n views.

Data Access Pattern Like Repository but Not Completely

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.

Access Repository through Service or directly?

is itIa good coding standard to allow ASP.NET MVC controller actions to access a repository directly (even though a service layer is present for the heavy lifting, e.g. LoginService.Authorize() ) to retrieve, add, or update data? Or should everything go through the service, and from there to the repository?
For smaller applications/webs, i tend not to use service layer, because it just maps Repositories methods 1:1, and I loose KISS. But in the end, it depends on business model; repository abstracts db access, and services encapsulates logic.
It's better to go through the service layer (depending on how you've implemented it though), because that's the point of it - to be a single access point, thus any business-specific things you do there, are represented and implemented across all callers.
It really depends on the complexity. If you're dealing with any transcation scoping, I'd definitely decouple that away from the controller into your service layer.
In my opinion it will depends on your design/architecture. What's the purpose of a repository ? Do CRUD operations (Create, Read, Update and Delete).
If you're using the anemic domain models in a classic three-tiers architecture all logic applied to the models are made in the services.
In this case the choice is obvious : You shouldn't call the repository directly.
Why ? Since your models are silly and the logic is in the services you could create invalid models. If you can call the repository you could create/update an invalid model in database. If you call the services it should be able to correct or fill your model before create/update it.
If you're using a rich domain model in an onion architecture it's different. Since your models are supposed to be always valid (when you create one from the constructor or from the factory all validations has been performed and when you update one it's the same thing) you can without any problem call directly the repository.
In this context all the logic is in the models directly and the services are just used to stored the logic that doesn't belong to one model specificly.
Now the question is not "how to use repository" but "what design/architecture do I need ?" and the first question will be answered :-)

Data Access Layer

how we can create a generic data access layer that can be used by any asp.net application using different datasource provider or webservices?
Can we create data access layer for application that consumes webservice?
You might look into the Repository Pattern. Repository is a facade that presents persisted objects as though they are in a collection in memory. Whichever provider you choose to get data is hidden behind the Repository interface.
IRepository with LINQ to SQL
Code Project Tutorial
A sample by Fredrik Kalseth
You have plenty of options! :-)
You mention you want to use the data access layer (DAL) from asp.net and web services. No problem.
Basically, what you need to figure out is a basic design you want to follow, and encapsulate the DAL into its own assembly which can be used / referenced from various consumers.
There are numerous ways of doing this:
create a Linq-to-SQL mapping for your tables, if you're using SQL Server as your backend, and use the Linq-to-SQL entities and methods
create a repository pattern (for each "entity", you have an "EntityRepository" class, which can be used to retrieve entities, e.g. EntityReposity.GetByID(int id), or EntityRepository.GetByForeignKey(string fk) or whatever
use some other means of accessing the data (NHibernate, your own ADO.NET based mapper)
you could actually also use webservice calls as your data providers
Your biggest challenge is to define a standard way of doing things, and sticking to it.
See some articles - maybe they'll give you an idea:
Creating a Data Access Layer in .NET - Part 1
Building a DAL using Strongly Typed TableAdapters and DataTables in VS 2005 and ASP.NET 2.0
Try the tutorials at www.asp.net:
DataAccess
Woah, there are a ton of resources out there. Best advice to start is to find a pattern that you feel comfortable with and stick to it for the project, there is nothing worse then changing your mind 3/4 the way in.
One that I have found and like to use is the Repository or Provider patter. The Repository pattern just makes sure you have standard access to repositories, like your store catalog or CMS system. You create an interface that in my case expose sets of IQueryable the object or the data model are just standard c# classes with now extra fluff POCO (Plain Old CLR Objects).
public interface ICMSRepository {
IQueryable<ContentSection> GetContentSections();
void SaveContentSection(ContentSection obj);
}
Then just implement the interface for your different providers, like a LINQ to SQL context, making sure to return the POCO objects as queryable. The nice thing about this is that you can then make extension methods off of the IQueryable to get what you need easily. Like:
public static IQueryable<ContentSection> WithID(this IQueryable<ContentSection> qry, int ID) {
return from c in qry select c;
}
//Allow you to chain repository and filter to delay SQL execution
ICMSRepository _rep = new SqlCMSRepository();
var sec = _rep.GetContentSections().WithID(1).SingleDefault();
The nice thing about using the Interface approach is the ability to test and mock it up or dependency inject your preferred storage at run time.
Another method I have used and is used in the ASP.Net framework a lot is the Provider model. This is similar except instead of an Interface you create a singleton abstract class, your implementations on top of the abstract class will then define the storage access means (XML, Flat file, SQL, MySql, etc). The base abstract class will be also be resonsible for creating it's singleton based on configuration. Take a look at this for more info on the provider model.
Otherwise you can look at this similar question.
IRepository of T is general good approach. This Interface should expose GetAll, GetByID, Insert, Delete and Submit methods.
But it's important to keep your business logic out of Repository class, and put it to custom logic/service class.
Also, if you return IQueriable in your GetAll method, what you can often see in various implementation of IRepository, UI layer can also query against that IQueriable interface. But querying of object graph should remain in Repository layer. There's a lot debate around this issue.
Look at using the Interfaces:
IDbConnection
IDbCommand
IDbDataAdapter
IdataReader

Categories

Resources