Understanding the MVC Architectural Pattern
Assumptions:
1..NET4 and vs2010/above is installed on system.
Code Download: Click Here to download entire solution
2. Knowledge .Net Basics with C#
Note : I am using Microsoft vs2010 MVC template for creating this Article Gallery Application Next Series i will demo how we can separate Model and Database Repository to fallow Separation of Concern [SOC]
How ASP.NET MVC Works
Assumptions:
1..NET4 and vs2010/above is installed on system.
Code Download: Click Here to download entire solution
2. Knowledge .Net Basics with C#
Note : I am using Microsoft vs2010 MVC template for creating this Article Gallery Application Next Series i will demo how we can separate Model and Database Repository to fallow Separation of Concern [SOC]
How ASP.NET MVC Works
Introduction
MVC is the just separation of model, view and controller It's simply a way to Avoid mixing code from the three categories into one class.MVC is architectural pattern which separates the representation and the user interaction. It's divided in three broader sections, "Model", "View" and "Controller". Below is how each one of them handles the task- The "View" is only responsible for look and feel.
- Model represents the real world object and provides data to the "View".
- The "Controller" is responsible to take the end user request and load the appropriate "Model" and "View".
Models represent data. A model can be as simple as a single object or a complex type with many collections of objects within it. The model should not include implementation details. A model may have many associated views.
View:
The view typically represents a user interface component that is bound to a model. The view can display the data and allow a user to modify the data. The view should always reflect the state of the model.Controller:
The controller provides a mechanism for the user to interact with a system by defining how the user interface reacts to user input. It is responsible for exchanging and interpreting messages between the view and the model. Let us assume we are going to create Article Gallery with below option using Database First Approach Adding Article- Updating Article
- Deleting Article
- View Article
- Search Article
- View Article Detail
Designing a Data Model
In MVC, M stands for model, and it’s the most important character in the pattern. Your model is a software representation of the real-world objects, processes, and rules that make up the subject matter, or domain, of your application. It’s the central keeper of data and domain logic (i.e., business processes and rules). You don’t need much of a domain model for the Article Gallery application, but there is one obvious type of model object that we’ll call Article..
Adding a Model Class
For below explanation i will be using Database First Model.Before i start creating model i just want to say that there are three approaches to using Entity Framework (EF) – Model First, Database First and Code First. Here you see the explanation of each.Database First :In the database first approach, we are creating the entity framework from an existing database. We use all other functionality, such as the model/database sync and the code generation, in the same way we used them in the Model First approach
Model First:In the Model First approach, the database model is created first using the ORM designer in Visual Studio. Once the model consisting of entities and relationships has been designed, the physical database will be generated from the model. .
Code First: In Code-First Approach, we create the classes first and then generate the database from the classes directly. In code first, we won’t use the Entity Designer (for editing .edmx files) at all.
So when should one choose one method over the others? Here is a simple comparison of the advantages all three approaches. Fact is that all three approaches lead to creation of Model and using any of these approaches is just matter of taste
Model First:
- Good support with EDMX designer
- We can visually create the database model
- EF generates the Code and database script
- Extensible through partial classes
- We can modify the model and update the generated database.
- An existing database can be used
- Code can be auto-generated.
- Extensible using partial classes/ T4 templates
- The developer can update the database manually
- There is a very good designer, which sync with the underlining database
- There is full control of the model from the Code; no EDMX/designer
- No manual intervention to DB is required
- The database is used for data only
Following Conventions for Controller Classes
Controller classes must have names that end with Controller, such as ProductController, AdminController, and HomeController. When referencing a controller from elsewhere in the project, such as when using an HTML helper method, you specify the first part of the name (such as Article), and the MVC Framework automatically appends Controller to the name and starts looking for the controller class.Following Conventions for Views
Views and partial views go into the folder /Views/Controllername. For example, a view associated with the ProductController class would go in the /Views/Product folder. The MVC Framework expects that the default view for an action method should be named after that method. For example, the default view associated with an action method called List should be called List.cshtml. Thus, for the List action method in the ProductController class, the default view is expected to be /Views/Product/List.cshtml. The default view is used when you return the result of calling the View method in an action method,like this:
return View();
You can specify a different view by name, like this:
return View("MyOtherView");
Notice that we do not include the file name extension or the path to the view. When looking for a view, the MVC Framework looks in the folder named after the controller and then in the /Views/Shared folder. This means that we can put views that will be used by more than one controller in the /Views/Shared folder and the framework will find them.
Following Conventions for Layouts
The naming convention for layouts is to prefix the file with an underscore (_) character, and layout files are placed in the /Views/Shared folder. Visual Studio creates a layout called _Layout.cshtml when all but the Empty project template is used. This layout is applied to all views by default through the /Views/_ViewStart.cshtml file.If you do not want the default layout applied to views, you can change the settings in_ViewStart.cshtml (or delete the file entirely) to specify another layout in the view, like this:@{ Layout = "~/Views/Shared/MyLayout.cshtml" } Or you
can disable any layout for a given view, like this: @{ Layout = null; }
What Is a Persistence Framework?
A persistence framework is a library used to simplify accessing and storing information. In practice, this means how we write our code to communicate with the relational database management system (RDMS). The current trend in the industry is to use object-relational mapping (ORM) persistence frameworks. These are abstract things such as tables, columns, and rows, and they allow us to work primarily with objects. Popular open source ORMs for .NET include :
- NHibernate
- Entity Framework
- LINQ to SQL
Deciding Between MVC and Web Forms
Decision: Let us take detailed look at the advantages and disadvantages of each,and make the case for MVC.First, I have to say that Web Forms gave us a great and smooth run for long. I have used Web Forms on many successful projects.Many of them are still in active use almost five years after they were initially deployed. So ,Fact is that WebForm are alive and will remain alive in market parallel to MVC because It has got huge advantages like its rich control support and rich server side event model.Reality is that No technology is perfect. They all have things they can do very well, and areas where they lack and can use improvement. This section takes an honest look Web Forms and MVC, and discusses the benefits and drawbacks of each.
Web Forms Disadvantages
• Hard and Toughest part is post-backs:• ASP.NET controls are not as effective as modern client-side libraries: The large library of UI widgets that come with Web Forms, which seemed like such an asset a few years ago, are also falling out of favor. The JavaScript UI libraries that are freely available from jQuery and others are just plain better than what is available in ASP.NET. They render faster, do not rely on the dreaded ASP.NET view state, and are beautiful. While many of the controls have been updated in the latest release of ASP.NET, most of them still use deprecated rending techniques such as using HTML tables for layouts. They are also difficult, if not impossible, to program against from client-side code.
• The code-behind pages often break separation of concerns: While a disciplined programmer can create clean code-behind pages, in many cases, developers break the separation of concerns by manipulating the user interface in the code-behind page, or even worse—directly manipulating the database from the code behind. This often leads to huge, fragile, unmaintainable, and untestable code.
• View State: Web Forms uses a concept known as view state, in which a hidden field contains the values of all server-side controls, encoded in a big nasty string. This data is sent on every postback, which slows response times and increases bandwidth usage. For pages that use controls such as a grid view, the view state can be hundreds of kilobytes.
• Client-side code is difficult to work with: The client-side code generated by Web Forms is difficult to read and very difficult to code against. First, each UI Widget that you drag onto a page is attached to a DLL with possibly 20 embedded script files. In many cases, using just one of these controls on a page will lead to all 20 of these scripts being included on your page in
• Another pain point for client-side developers is the automatic naming convention used for client-side elements With the default setting, you get ids in the form of ctl00_LoginView1_LoginName1. For nested UI elements, it gets even worse. ASP.NET 4 offers a mechanism to aid in this situation by allowing you to specify how the client ID can be generated.
• Code-behind pages can't be tested with automated testing tools: Code-behind pages are simply not designed for this scenario. There is no easy way to abstract the code-behind pages so that a unit test framework can be used. If you were planning on using a test-driven development(TDD) approach with Web Forms, you will have a difficult time.
MVC Disadvantages
• Learning curve: If you are coming from Web Forms, there is a substantial learning curve associated with moving to MVC. Having to learn a new technology on a deadline is never simple nor can be achived easily.• More complex: The MVC code separates the code that makes up a page into a minimum of three files. If you are not planning on doing unit testing, and don’t like HTML coding, MVC may not be the best choice.I mean when development cycle includes test driven development TDD then MVC is the best choice otherwise it sucks..
• No drag-and-drop form creation: If you use the MVC Framework, you will be hand-coding your HTML. In fact, Visual Studio does not even offer a visual designer for MVC Views when using the Razor view engine. For most teams, the learning curve is hardest to move past. For Prototyping there is no support in Razor .
Difference between LINQ to SQL and Entity Framework
LINQ to SQL is an object-relational mapping (ORM) framework that allows the direct 1-1 mapping of a Microsoft SQL Server database to .NET classes, and query of the resulting objects using LINQ. More specifically, LINQ to SQL has been developed to target a rapid development scenario against Microsoft SQL Server where the database closely resembles the application object model and the primary concern is increased developer productivity. LINQ2SQL was first released with C# 3.0 and .Net Framework 3.5.
- LINQ to SQL supports a wide breadth of abstractions
- LINQ to SQL support domain Model
- Linq to SQL is only for SQL
- LINQ to SQL is simple to use
- LINQ to SQL is used for rapid development.
- LINQ to SQL class uses the mapping only for the single table
- LINQ to SQL generate only dbml file
LINQ to Entities (ADO.Net Entity Framework) is an ORM (Object Relational Mapper) API which allows for a broad definition of object domain models and their relationships to many different ADO.Net data providers. As such, you can mix and match a number of different database vendors, application servers or protocols to design an aggregated mash-up of objects which are constructed from a variety of tables, sources, services, etc. ADO.Net Framework was released with the .Net Framework 3.5 SP1.
- Entity framework supports a high level of abstraction.
- Entity framework support conceptual data mode.
- Entity Framework will have ability to target different database engines in addition to Microsoft SQL Server.
- Entity framework is complex to use.
- Entity framework is slower development but has more capabilities.
- Entity framework map a single class to multiple tables
- Entity framework generate the three xml files csdl, msl and ssdl.
.NET is going on along with both patterns (MVC & Webforms).Now all depends on need and requirement.So,based on need we can pickup right one.
How these Articles will be structured
During the course of these articles, I m going to explain how to Architect End to End Application using MVC with Entity Framework, starting with the ones at the beginning of the MVC and finishing with the Complate Application Architecture includes. :- Seperating Model and DataAccess from Entity Model
- Applying Validation Using the ASP.NET MVC 4
- ASP.NET MVC Defining an application architecture:
- ASP.NET Application Development Using MVC
- How do architect an ASP.Net MVC app with EF?
- Using T4 to Generate POCO Classes
Separating Model from ADO.NET Entity Data Model
Assumptions:
1..NET4 and vs2010/above is installed on system.
Code Download: Click Here to download entire solution
IntroductionI wrote a post a last weeks about Understanding MVC Pattern . If you have read that post first (it might be a good idea) you can click here to read it now.Since it was posted, I have noticed that a few people visit the post every day and they might be waiting for next post.At, the end of my article i have clearly mentioned that i will be cleaning this application in future posts . So, as promised, I am going to fallow some steps to achieve this. So,this post will be useful as well as helpful i hope.
Here you see list of Projects(layers) to the solution:
– This layer will contain the POCO objects
– This layer will interact with the database and will contain our Entity Framework file FaithDataLayer in my case
– This layer calls the data layer and implements business rules(FaithBusinessLayer) in my case
This layer contains the actual WCF or Other service that can be accessed by external websites (FaithServiceLayer) in my case
– This is a MVC website that will be accessed from browser (Faith.MVC.Sample) in my case
For Solution layers, you can name your projects whatever you want as long as you know what each layer is for. Model, Datalayer, BusinessLayer .... are just naming conventions that I have choose.
This is what it looks like in my solution explorer:
Once that has been done, click on the "ADO.NET Entity Data Model" name the file as per your naming convention and then save it by clicking "Add".
At this point, the "Entity Data Model Wizard" appears. Fallow below steps
So now that you are looking at the Entity Framework file that you just created, right click on the canvas of the Entity Framework Model. Just select "Add Code Generation Item .
This will bring up another window showing the "Installed Templates" as shown in the screenshot below. Once the "Add New Item" window pops us, we want to select the template called "ADO.NET POCO Entity Generator". Again name it as per your naming convention . I prefer to keep the name the same as what I chose for the Entity Framework itself.
if you cannot find this template installed in your copy of Visual Studio, you can find instructions on searching for and installing templates in Google. Once you save the "ADO.NET POCO Entity Generator", two new files will be created in your data project as shown in below figure. In my project, they are: "FModel.Context.tt" and "FModel.tt". At this point if you will try to compile solution you will not get any problem but there are certain things which need to be observed. First of all, underneath the new template files (with .tt extension), you will see that several new classes based on Model have been added to your DataAccessLayer project, as shown in the graphic below
Each of these new classes maps to an object in your Entity Framework model, which, in turn, map to a table in your database. These files are auto generated each time that the template file is saved, but if you open one up you will see that it is just a standard class with properties defining each column in the table. You will also notice that they are partial classes. In Future series we will also see how to modify template to customize our classes.
Final Step to Separate your Model(POCO Classes):
Now that the Entity Framework Model is created, we are ready to separate model classes from FaithDataLayer.
To move our POCO’s from the FaithDataLayer to the FaithModel is just Cut and Paste process. Right click on the FaithDataLayer Project and select FModel.tt to cut and paste the name (FModel.tt). Select "Cut" from the context menu, then right click on the FaithModel project and select paste. All of its associated classes should now have moved to the FaithModel project. Our only problem now is that by moving the template we have broken the link between it and the Entity Framework model upon which it depends to create the POCO classes. To do so, open the template file(FModel.tt) that is now in the FaithModel project. Just open FModel.tt try to find line of code that reads something like this:
And change it to a path where it can find the Entity Framework model over in the
FaithDataLayer project, like so:
When you click save, you will know immediately if this worked. If it did, the class
files for your database objects will be regenerated as they should be. If the path
that you entered was incorrect or some typing mistake is there, however, you will
receive a error . a big error.... If you are on Happy Path i mean if solution builds
successfully then just remove System.Data.Entity reference from FaithModel
projects if exists then try to build you model project successfully without reference
of System.Data.Entity.
Project References Now we are can start adding project references. Just set references like shown below:
FaithDataAccessLayer Project should Refer FaithModel Project
FaithBusinessLayer Project should Refer FaithDataAccessLayer Project & FaithModel Project
FaithServiceLayer Project should Refer FaithBusinessLayer
FaithModel Project – No Project References
Note: Please,don't touch or think about Service layer,BusinessLayer yet because we will use them at right time,i mean in future posts
Hope this helps...
Assumptions:
1..NET4 and vs2010/above is installed on system.
Code Download: Click Here to download entire solution
IntroductionI wrote a post a last weeks about Understanding MVC Pattern . If you have read that post first (it might be a good idea) you can click here to read it now.Since it was posted, I have noticed that a few people visit the post every day and they might be waiting for next post.At, the end of my article i have clearly mentioned that i will be cleaning this application in future posts . So, as promised, I am going to fallow some steps to achieve this. So,this post will be useful as well as helpful i hope.
Create the Solution in Visual Studio2010
I will modify existing solution or you can create new one in a same way for Article Gallery Application which is developed to keep track of members/authors and their respective articles . if you have not gone throught it just click to see here Article Gallery Application . So to begin with, let’s create a modify existing solution and then add projects to it that will make the different layers of our application. Using Visual Studio,add in the following projects like shown belowHere you see list of Projects(layers) to the solution:
– This layer will contain the POCO objects
– This layer will interact with the database and will contain our Entity Framework file FaithDataLayer in my case
– This layer calls the data layer and implements business rules(FaithBusinessLayer) in my case
This layer contains the actual WCF or Other service that can be accessed by external websites (FaithServiceLayer) in my case
– This is a MVC website that will be accessed from browser (Faith.MVC.Sample) in my case
For Solution layers, you can name your projects whatever you want as long as you know what each layer is for. Model, Datalayer, BusinessLayer .... are just naming conventions that I have choose.
This is what it looks like in my solution explorer:
Entity Framework Model and POCO’s
Now right click on the FaithDataLayer project in your solution and select Add > New Item … When the dialog box appears, click on " FaithDataLayer" in the "Installed Templates" section like belowOnce that has been done, click on the "ADO.NET Entity Data Model" name the file as per your naming convention and then save it by clicking "Add".
At this point, the "Entity Data Model Wizard" appears. Fallow below steps
- Select "Generate From Database" on the "Choose Model Contents" page.
- Click Next
- Click on "New Connection" and then use the "Connection Properties" dialog to build the connection string to your database. I recommend that you use "SQL Server Authentication" with an account that is set up with only the necessary permissions for your applications
- Click on Test Connection, if the popup says "Test connection succeeded" then click on the "OK" button
- Click on the radio button labeled "Yes, include the sensitive data in the connection string" (this can be encrypted later if you wish)
- Click the check box labeled "Save entity connection settings in App.Config as" and then give proper connection a name
- Click Next
- Select all the database objects that you want to include in the Entity Framework (Mostly database tables)
- Again give name for the Model Namespace as per naming convention
- Click "Finish" to Wrap up
So now that you are looking at the Entity Framework file that you just created, right click on the canvas of the Entity Framework Model. Just select "Add Code Generation Item .
This will bring up another window showing the "Installed Templates" as shown in the screenshot below. Once the "Add New Item" window pops us, we want to select the template called "ADO.NET POCO Entity Generator". Again name it as per your naming convention . I prefer to keep the name the same as what I chose for the Entity Framework itself.
if you cannot find this template installed in your copy of Visual Studio, you can find instructions on searching for and installing templates in Google. Once you save the "ADO.NET POCO Entity Generator", two new files will be created in your data project as shown in below figure. In my project, they are: "FModel.Context.tt" and "FModel.tt". At this point if you will try to compile solution you will not get any problem but there are certain things which need to be observed. First of all, underneath the new template files (with .tt extension), you will see that several new classes based on Model have been added to your DataAccessLayer project, as shown in the graphic below
Each of these new classes maps to an object in your Entity Framework model, which, in turn, map to a table in your database. These files are auto generated each time that the template file is saved, but if you open one up you will see that it is just a standard class with properties defining each column in the table. You will also notice that they are partial classes. In Future series we will also see how to modify template to customize our classes.
Final Step to Separate your Model(POCO Classes):
Now that the Entity Framework Model is created, we are ready to separate model classes from FaithDataLayer.
To move our POCO’s from the FaithDataLayer to the FaithModel is just Cut and Paste process. Right click on the FaithDataLayer Project and select FModel.tt to cut and paste the name (FModel.tt). Select "Cut" from the context menu, then right click on the FaithModel project and select paste. All of its associated classes should now have moved to the FaithModel project. Our only problem now is that by moving the template we have broken the link between it and the Entity Framework model upon which it depends to create the POCO classes. To do so, open the template file(FModel.tt) that is now in the FaithModel project. Just open FModel.tt try to find line of code that reads something like this:
string inputFile = @"Fmodel.edmx";
string inputFile = @"..\FaithDataLayer\FModel.edmx";
Project References Now we are can start adding project references. Just set references like shown below:
FaithDataAccessLayer Project should Refer FaithModel Project
FaithBusinessLayer Project should Refer FaithDataAccessLayer Project & FaithModel Project
FaithServiceLayer Project should Refer FaithBusinessLayer
FaithModel Project – No Project References
Note: Please,don't touch or think about Service layer,BusinessLayer yet because we will use them at right time,i mean in future posts
Hope this helps...
"Thanks for sharing this.. its is so helpful
ReplyDeletekhatm e Nabuwat
"