Running custom queries in ASP.NET MVC - c#

I'm new to using the ASP.net MVC framework (and C# too). I have more experience using JSP + JSTL MVC framework. I want to know how to run custom queries if I need to do more complex sql.
In the JSP framework, I'm used to creating DAOs to query sql tables which doesn't seem to be the case in ASP.net. For ASP.net, I noticed that we use LINQ to do the querying over a DBSet object from a model.
My Questions:
Where do I write the custom query code? In the model?
How do I write it? Is it through some sort of db.execute statements?
Are there any configuration changes I need to make?
Examples and other resources would be nice.
I tried looking through the asp.net MVC tutorials on asp.net, but I couldn't find anything.

How you execute SQL queries depends entirely on what data access framework you are using. You can write plain SQL with ADO.NET and execute queries in a manner much like that you would expect.
In answer to the second part of your question, this should be done in a data access layer and be completely unrelated to your ASP.NET MVC application itself. Any necessary logic for instantiating and communicating with classes in that abstracted layer should reside in your controller (and, ideally, be loosely coupled from your application via the use of interfaces and/or service layers).
In this sense, yes, it belongs in the model. However, bear in mind that, conceptually, the 'M' in ASP.NET MVC is the domain model (i.e. the aforementioned data access layer), not the view model. The view model is just an independent wrapper that is designed to store relevant data for a given view and should - in most cases - be completely devoid of logic whatsoever.

In the JSP framework, I'm used to creating DAOs to query sql tables
which doesn't seem to be the case in ASP.net.
It is very much the same, you should have a separate DAL project with your DAO objects and reference those from your Business Layer (another separate project). The ASP.NET MVC project itself will add a reference to the Business Layer project which in turn will add a reference to the DAL. That way, you can keep a 3-tier architecture:
UI (ASP.NET MVC project)
|
|
Business Layer (POCO objects (= to POJO), validation, biz logic) - separate project(s), depending on whether you put your POCO objects in the same project or not.
|
|
Data Access Layer (You can use ADO.NET, EF (LINQ), etc.)
An ASP.NET MVC app usually is composed of 3 folders: Models, Views, Controllers but everything that's typically placed in the Models folder is really your Business Objects so I tend to get rid of that folder completely and I am left with just the Views and the Controllers folders. The views are just the html markup, pretty much. The Controllers classes simply call the methods from the business layer and passes the results to the views. So for example, a UserController class will look something like this:
public class UserController : Controller
{
public ActionResult Index()
{
var allUsers = UserBusLayer.User.GetAll();
return View(allUsers);
}
}

Related

3-Tier - Models reusing?

I am creating an application that has those three different projects:
ApiService (Web API 2)
BusinessLogic (Class Library)
DataAccess (Class Library)
ApiService has a reference to BusinessLogic
BusinessLogic has a reference to DataAccess
DataAccess uses Entity Framework with code first approach so it contains the models for the database tables.
My question is, what is the best approach or best practice regarding the models for Business and Service Projects?
I have read that Service project should not be using the models of the DataAccess project, so where should I create that models, in Service or in Business?
Thanks in advance.
Separate BL(Business logic)/Presentation layer models from DAL(Data access layer) models always.
Add one more layer between them which will do the mapping, use Automapper or somethogn custom. So when you are passing data to DAL models will be mapped to entity models, and when BL is getting the data from DALsame thing, map entity models to BL models,
Why?
The way how you are persisting your data in your database may be rather different from how you are going to present it to the user. The data may have to be obtained from several entities, joined by relationships, constructed at run time again by joining from other tables, etc. How you are going to present it to a user may be simplified and different than it is persisted, so you can hide that complexity which is needed for the database.
I don't know if this is best practice, but I have made many projects that contain a lot of shared logic and functionality between windows services, Web APIs, etc. They have all followed something similar to this:
Wrapper - Contains interaces, models, and code to make calling the WebAPI from another .NET project easier. Has no references to the other projects at all
Core - Contains all the meaty business logic. Service layer, data access layer, helper classes, etc. References Wrapper and anything else needed to function
WebAPI - Contains only code necessary for creating a WebAPI around the service layer functions in Core References Wrapper for models/interfaces, and Core for business logic
Other projects that use Core would be similar to the WebAPI one. Examples would be a console app for scheduled tasks, Windows service for continual data processing, etc.
This results in what I've seen some people refer to as a "mega solution" or similar, but so long as you're keeping your code to one domain you're not creating a mess.

Generating DTO classes from DbContext via Text Templating

Please bear with me as I am new to MVC and WCF and may be asking the wrong question.
I am trying to write a WCF service and an MVC web application over an existing project that contains entity, data and business layers. The MVC and WCF components would then replace an older web service and WebForms application which worked very diferently and did not use modern practices.
I see the need to generate DTO objects against all Entity objects and was wondering how we can generate them. Through reflection, digging into the DbContext or some other method.
Furthermore, I also want to generate repository partial classes minimizing the need to maintain hand-written code for a large data model.
How do large development teams do this?

Layer ASP.NET MVC Project

I am trying to understand the concepts of a good designed project.
I am using ASP.NET MVC and i am trying to create a layered (pluggable) project.
The current project structure what i have now is this:
LayeredProject - the MVC Project containing Controllers
LayeredProject.EntityFramework - contains all the POCO classes used for database. (i am using Code First approach)
LayeredProject.Model - this should contain all the business objects used in the project.
Saying that the project is a eCommerce website, i would structure it like this:
In the LayeredProject.EntityFramework project i have classes which corresponds to the database tables. Category, Product, User. This project is used only for saving and loading data from database, and those objects should not be used for other purposes. This project has a reference to LayeredProject.Model project.
In LayeredProject.Model project i store all the objects i work with, which most of them are exactly copies of LayeredProject.EntityFramework POCO's objsects and some other Services Classes used.
In LayeredProject i keep all my ViewModels classes, Controllers, and different UI logic. This project has a reference to LayeredProject.Model project.
First of all, i am not sure that this is the right way of doing this.
And, it this is the right way of doing it, then i get a little confused because i will have a duplicate of my POCO classes in EntityFramework project and also on Model project.
Please help me understanding this
You can Design Your Project using layered structure as well using MVC. The Controller and view part should stay intact. You can divide the business logic part as many layers as you want. The model should come as a result of the number of layers you are expecting. For this keep your business logic in a separate project (not neccessary: it can be there in web project itself), refer the dlls from that project to the MVC web solution. Pass the models which are generated as a result of database querying to the web solution and with the help of controller render the view.(I have done my project using this style)
The MVC project should contain:
view models: models for the views, i.e. models that are very specific to render each view (these model are not the M in MVC). This models usually contain the data which must be shown or edited in the view, as well as aditional necessary information to render the view: for example, if the view must render Drop Down Lists, the view model should contain the corresponding SelectList or IEnumerable to populate the list. You can use mappers, like AutoMapper or ValueInjecter to move data from the business entities (entities coming from the Business Layer) to the view models, and viceversa. Or if appropriate, you can use directly the business entities as properties in the model view (the view model doesn't need to be flat: it can contain objects as properties)
views, strongly typed with the view models
controllers: this controllers use the Business Logic (that is the Model, the M in MVC) to control the application flow, to create and provide the model views for the views, and to react to the user actions
UI helper: I usually add this layer to fulfill the DRY principle. I.e. if I have to prepare a SelectList and it's going to be used in many views, I do it in this layer, and use it from all the necessary places. This can include calculations, orderings, or anything tighly related to the UI, so it doesn't fit in the Business Layer (Model). This uses the Business Layer, and provides data specific for the Views.
Those are the specific and critical parts of MVC, which includes the VC in MVC (views and controllers) The M in MVC (Model) is the business logic which can be done 'as usual'. I.e. you don't have to do anything special in your business layer to use it with MVC. You can use the technology of your choice (a traditional DAL + BLL, WCF, WS, or whatever you want).
This is something which works well for LOB applications. Of course, if you're making a toy application, you can forget this all and make something more monolythic. But I only recommedn this for very little applications with scarce maintenance needs.
These are examples of objects in several layers that allow to edit a "Pet":
Business Logic Layer:
PetService, a class which can be use to read, write, find, and modify pets (as explained above it doesn't matter how this is implemented)
Business Entity: it's the BLL entity for managing Pets. This could be a POCO object or a DDD entity:
Pet - int Id, int PetTypeId, string Name...
View Model: contains a Pet proerty, as well as a list of PetTypes, so that the view can render a drop down list for the PetTypeId:
PetViewModel - Pet ThePet, SelectList PetTypes
UI Helper: if the PetTypes is going to be used in more than one or two views, a PetUiHelper could provide this select list for all the views that require it:
PetUiHelper - GetPetTypesList()
Pet views: a strongly typed view for PetViewModel
Views\Pet\Edit.cshtml
PetController: uses the PetService to create the views, and their model views.
PetController - Edit(int id) --> returns an Edit view, woth its corresponding PetViewModel. There must be also an HttpPost Edit action which receives the user input in an specific model or the PetViewModel, or the Pet plus the Id or whatever. This depends on what you're editing.
Finally, if you know how to use DI, you can use Unity.Mvc or any of the other options to inject the Business Services in the controllers.
seems your using the Code First approach to build a data access, you can dig in this extensive article and gain more insight.
http://ofps.oreilly.com/titles/9781449320317/ch_AdvancedData.html
You probably have one too many layers in there, there should be no reason to separate the model with the business logic from the LayeredProject MVC layer itself unless you are planning to have a client app or some other separate project to access the model. In the MVC project you already have a model folder that can be used for that. However in the MVC project you should also add a "ViewModels" folder to keep models that are specifically used for the view concerns (e.g. DTO objects).
This project shows a nice simple way of keeping the things separate simply within folders in the MVC project: RacoonBlog Project. Although it uses RavenDB rather than EF the ideas are the same.
Most MVC apps I have worked were layered in this way
MVC Project: Had the controllers, views and models. The business logic resides in the model.
The Data Access layer (Persistence layer) : This project uses an ORM. (In your case entity frame work)
Classes that are mapped to the database tables reside in the Model and not the data access layer.

Using Existing Web Service within MVC 3

FYI, I'm working on my first MVC web application using MVC 3 and Razor with C#, and .NET3.5/4.0, and I'm looking for the "best pratice" approach for using existing web services in an MVC 3 application. From what I have figured out so far it looks like all I need to do is the following. Include a reference to the existing web service in the MVC project, create a Model for the data I desire to use in the application, create a Controller that makes the web service call that then fills an object created from the Model (reading about AutoMapper to see how this helps in that process), and then create a View to display the data that was translated into the MVC view model.
The part that I'm having questions about is what is the best way to retrieve and create/update the data from the web service. Maybe I'm over complicating this but it seems like I'm missing something.
Do I need to create a "Domain Model" that maps to the data retrieved from the web service and then create "View Models" that map to the domain model, and then use the View Models within the MVC 3 application?
Basically I'm looking for input on how best to use existing web services as my data access layer.
On your data access layer you would open the connection, get the raw data and then close it. Identically to how you would get data from your database. You would then convert this raw data to your business layer (domain model) via a data adapter. Then any top level applications, such as your MVC3 website, will convert this domain model into an approriate view model, along with any other data for rendering, again through a data adapter.
The main argument for doing it this way is that the service is now accessible to any top tier application that requires it. It is also makes logical sense to put any sort of data retrieval methods in your data access layer, since that's logically what the data access layer is designed to do.
There is always the temptation to simply access the service from your controller, but separation of concerns might suggest this is a bad way to structure your code. You should encapsulate the service as a domain/business layer service for your applications.
So in short, you don't need to, but best practice suggests you should. It can feel tedious sometimes when there is little or no conversion between layers, but it often helps to stay consistent.
To obey the MVC pattern and its separation of concerns, calling the database must be in the model. And if this web services calls the database somehow, it should be at the Model level.
let the UI talk to the model directly, in case later u needed a webservice to integrate with another system you can create a service which calls that model
And you may want to cache it if its read-only

Entity Framework and 3 layer architecture

I have a three layer architecture program. The questions are:
1. Data access is the layer of EF?
2. If i want to use an entity generated by EF from Presentation Layer, then i reference the Data Access, but this violates the principles of 3 layered architecture.
Microsoft Spain released a pretty good documentation, guide and sample application for N-layered applications on codeplex, you can look it up here:
http://microsoftnlayerapp.codeplex.com/
You will find many directions and helpful implementation patterns there.
hth.
Yes EF would be your Data Access Layer.
With EF you can use T4 templates with POCO support, you can then extract these POCO into a seperate dll and this will be reference from all of your layers.
What type of application are you building? If you are building an ASP.NET MVC 3 application, you can have your View be the presentation layer, your Model is your data access (which can use EF) and the controller and / or Action Filters can contain your business logic and in this scenario you will be using your EF Model in the presentation layer but still satisfy the separation of concerns principle.
EF does two things: -
1) Generates an domain model for you (optional, but commonly used)
2) Gives you the ability to query / modify your database via that domain model.
This can give the appearance of blurring the lines between domain model and data access but the two are indeed separate.
As long as you're not doing stuff like creating object contexts and writing queries directly in your presentation tierthen IMHO you are not breaking abstraction - the only thing you are "breakin"g is the fact that you will need to reference System.Data.Objects (or whatever the EF dll is) in your presentation project(s) (which is just a physical artifact) unless you go down the route suggested by Jethro to generate your domain model into a separate project.
For the three tier architecture. I would consider doing Abstraction using Domain Model and Data model pattern rather then doing direct EF from Presentation Layer.
So the idea is that you have your Data Model which has EF POCO classes with Repositories which knows how to access these Classes for various CRUDs.
Your Domain Model would have models related to your Client (so you can put various ViewModels or Validation related code), It can be a WPF or MVC web app.
Now between these two there is a business which talks to both Domain and Data models.
Your Presentation Layer does know nothing about the EF/Data Layer/Repository. When you want to introduce new Data Framework or database, you just need to write new repository classes and data models classes (which prob. be with some sort of code gen).
This also allows your code to be Unit testable as well.

Categories