Saturday, 28 June 2014

Simple Explaination of MVC Architectural Pattern with Example

Understanding the MVC Architectural Pattern
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]



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".

Complete flow of MVC?
To understand the the power of MVC you need to understand the Life Cycle, I could go in to great detail about the ASP.NET Life cycle, but I have found a number of very good articles already providing good amount of information on the Life Cycle.  Before going to the pages here is a simple flow diagram of the steps the MVC process goes through
Below are the steps how control flows in MVC (Model, view and controller) architecture:-
  1. All end user requests are first sent to the controller.
  2. The controller depending on the request decides which model to load. The controller loads the model and attaches the model with the appropriate view.
  3. The final view is then attached with the model data and sent as a response to the end user on the browser.
ASP.NET MVC represents a simpler, more testable framework for developing web applications in Microsoft .NET.When people reference the acronym MVC, they are most likely referring to the software design pattern. Model-View-Controller is a user interface design pattern that separates display , data, and flow of control into different objects  The view represents the screen and user input, the controller acts to coordinate the input/output from the view, and the model is the data structure that is passed between the two as shown in below figure 1. The pattern helps separate the display, interaction, and data logic.
URL Routing Engine:
In the standard ASP.NET model (or Post-back model), the URLs map directly to the physical files
So when we make a request to a page, say ViewArticle.aspx, the run-time compiles that page and returns the generated HTML back to IIS to be displayed by the client browser. So we have a one-to-one relationship between the application URLs and the page.But in the MVC framework, the URLs map to the controller classes.
Therefore, the URL is sent to IIS and then to ASP.NET run-time, where it initiates a controller class based on the URL, using the URL routes, and the controller class then loads the data from the model, with this data finally being rendered in the view as per convention rather than configuration The controller classes uses URL routing to map the URLs, which in simpler terms means rewriting URL. We can set up the rules for which URL is to be routed to which controller class. The routing will pick up the appropriate controller and pass in the query string variables as necessary.
Open the global.asax.cs file and examine the following code:
public class MvcApplication : System.Web.HttpApplication
            { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("
            routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new
            { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } protected
            void Application_Start() { RouteConfig.RegisterRoutes(RouteTable.Routes); } } 
The RegisterRoutes() method contains the URL mapping routes. Initially we have only the default rule set:
routes.MapRoute(name: "Default" ,url:"{controller}/{action}/{id}",defaults:
            new { controller ="Home", action = "Index", id = UrlParameter.Optional }); 
This URL mapping engine comes from System.Web.Routing.dll, which can be used independently, without the ASP.NET MVC framework, That mean URL routing can be used with  standard ASP.NET web applications also.
The MapRoute() method, which handles URL routing and mapping, takes three arguments:
  1. Name of the route (string)
  2.  URL format (string)
  3.  Default settings (object type)
In our case, we named the first route "Default" (which is the route name) and then set the URL as:
The Controller here is the name of the controller class. action will be the method that needs to be invoked inside that controller class. id would be the parameters that need to be passed, if any. In the default arguments, we create a new object and call it "Home", set the action to Index, and do not pass parameters to it
The var keyword and anonymous types: We normally use classes to wrap behavior and properties, but in C# 3.0 and above, we can create the types anonymously without needing to create classes for them. This can be useful when we need to create light weight classes that have only read only properties. We can use the anonymous syntax to create those types without the need to create a class for them. We can use the new " var " keyword to hold such anonymous types, for example:
var ch = new {readOnlyProperty1 =value1,readOnlyProperty2
            = value2 };
It is important that we name and assign a value to each of the properties that we are creating. Like
var ch = new {Name ="Shabir",City "Bangalore" };
What will be the type of the properties?
they will automatically be cast to the data types of the values of the properties specified. The anonymous types will always be derived from the base object class directly. They can only be used within class members and cannot be passed as method arguments (unless they are boxed), return values, or be specified as class-level variables. Once the type is created, it cannot be changed into another type.So we create a new anonymous type as the last argument of the MapRoute() method, passing in variable defaults with three properties, namely controller, action, and parameter.Now have the Default.aspx page under the root directory, which acts as a redirecting page to the main home page of the site (which is /View/Home/Index.aspx). We cannot directly set that as the "default" page since we are using URL routes to process pages instead of using physical files in the URLs. So in the code-behind of our Default.aspx page, we have a simple redirect:
public void Page_Load
(object sender, System.EventArgs e) { Response.Redirect("~/Default"); } 
So the run time will first set up routes in the global.asax page, then it will process the Default.aspx page. Here it faces a redirect to this URL: /Home.


Fallow below steps to open and create solution
1. Open Vs2010/Above (better open as Admin) & choose MV4 Template from list and name it as per your naming convention.For me Faith.MVC.Sample & press OK
2. You will see below screen .Just choose Internet Application Icon from List like shown below & press OK
3.You will see below screen with default MVC solution like shown  below
4.Now you have default solution open .The Model View Controller (MVC) pattern is a popular design pattern used in many software systems  because it  separates a software module into three distinct layers each with a specific role while  using visual studio you will get below shown solution created by default(below).
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.


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.


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
Let us first create Model.
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.
Database First:
  • 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
Code First:
  • 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
Use Solution Explorer to add a new ADO.NET ENTITY DATA MODEL Like shown below
  1. Right Click on Model Folder of the solution explorer and Click on Add-> New Item like show below.Fallow all the steps as shown
Here You can choose existing connection from dropdownlist or just create new connection.
If New Connection is clicked then you will see below screen
After Selecting database just Click on Test Connection button .if you get message like connection succeed like below then proceed
Select tables you want to include in Model.My case I have selected checked tables
Next you will see you model like shown below
Now you can dive into Model1.Designer.cs and see how Entity Framework has generated data access code for you without writing a single line of code.For now we will not touch this model except remembering ObjectContext Class Name which is FaithDbEntities as shown above.We will use this model as is; because we just want to see how MVC Application works .
Adding Controller
Adding Controller  is just simple .You just need to Right click on Controller folder and add New class  as shown below or you can use existing/default HomeController
Adding View
Create Folder with Article name and Right Click on it to Add View like shown below
Recapping whole Example Controller, Model, and View Code
public class ArticleController : Controller { private
            FaithDbEntities _dbContext = new FaithDbEntities();
 public Article CurrentArticle
            { get; set; } // GET: /Article/ public ActionResult ArticleHome() { return View();
            } [HttpPost] public ActionResult CreateArticle(Article entry) { entry.ArticlePubsDate
            = DateTime.Now; entry.AuthorId =1;//owner always will change in next iteration _dbContext.Articles.AddObject(entry);
            _dbContext.ArticleAuthors.Include("AuthorId"); _dbContext.SaveChanges(); return
            View("Created"); } public ActionResult CreateArticle() { var articleCategoryData
            = _dbContext.ArticleCategories.ToList(); ViewData["_ArticleCategory"] = new SelectList(articleCategoryData,
            // items "ArticleCategoryId", // dataValueField "ArticleCategory1", // dataTextField
            0); return View(); } [HttpPost] public ActionResult EditArticle(Article entry) {
            if (ModelState.IsValid) { //_dbContext.Entry(entry).State = EntityState.Modified;
            _dbContext.SaveChanges(); return RedirectToAction("Index"); } return View(entry);
            } public ActionResult EditArticle(int id) { Article article = _dbContext.Articles.Single(d
            => d.ArticleId == id); if (article == null) { return HttpNotFound(); } var selectedvalue
            = article.ArticleCategoryId; var articleCategoryData = _dbContext.ArticleCategories.ToList();
            ViewData["_ArticleCategory"] = new SelectList(articleCategoryData, // items "ArticleCategoryId",
            // dataValueField "ArticleCategory1", // dataTextField selectedvalue); ViewData["Article"]
            = article; return View(article); } public ActionResult ViewArticles() { using (var
            context = new Faith.MVC.DAL.FaithDbEntities()) { return View(context.Articles.ToList());
            } } public ActionResult ViewArticleDetail(int id) { CurrentArticle = _dbContext.Articles.Single(d
            => d.ArticleId == id); return View(CurrentArticle); } public ActionResult DeleteArticle(int
            id) { CurrentArticle = _dbContext.Articles.Single(d => d.ArticleId == id); if
            (CurrentArticle == null) return View("RecordNotFound"); Delete(); _dbContext.SaveChanges();
            return View("Deleted"); } [NonAction] public void Delete() { try { _dbContext.Articles.DeleteObject(CurrentArticle);
            _dbContext.SaveChanges(); } catch (DataException ex) { throw ex; } } public ActionResult
            SearchIndex(string articleTitle, string searchText) { var ArtLst = new List();

            var ArtQry = from d in _dbContext.Articles
                           orderby d.ArticleId
                           select d.ArticleTitle;
            ViewBag.movieGenre = new SelectList(ArtLst);

            var articles = from m in _dbContext.Articles
                         select m;

            if (!String.IsNullOrEmpty(searchText))
                articles = articles.Where(s => s.ArticleTitle.Contains(searchText));

            if (string.IsNullOrEmpty(articleTitle))
                return View(articles);
                return View(articles.Where(x => x.ArticleTitle == articleTitle));


@model Faith.MVC.DAL.Article @{ ViewBag.Title = "CreateArticle";
            Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Article Gallary</h2>
            <form method="post" action=""> <fieldset> <legend>Add Article</legend>
            <table> <tr><td>@Html.LabelFor(m => m.ArticleTitle)</td>
            <td> @Html.TextAreaFor(m => m.ArticleTitle, new { cols = "40", rows = "1"
            })</td></tr> <tr><td>@Html.LabelFor(m => m.ArticleCategoryId)</td>
            <td> @Html.DropDownListFor(m => m.ArticleCategoryId, ViewBag._ArticleCategory
            as SelectList) </td></tr> <tr><td>@Html.LabelFor(m =>
            m.AuthorEmailId)</td> <td>@Html.TextBoxFor(m => m.ArticleTitle) </td></tr>
            <tr><td>@Html.LabelFor(m => m.ArticleIntroduction)</td> <td>
            @Html.TextAreaFor(m => m.ArticleIntroduction, new { cols = "50", rows = "6" })</td></tr>
            <tr><td>@Html.LabelFor(m => m.ArticleBody)</td><td> @Html.TextAreaFor(m
            => m.ArticleBody, new { cols = "70", rows = "10" })</td></tr> <tr><td>@Html.LabelFor(m
            => m.ArticleSummary)</td> <td> @Html.TextAreaFor(m => m.ArticleSummary,
            new { cols = "70", rows = "4" })</td></tr> <tr><td><input
            type="submit" value="Submit Article" /></td><td></td></tr>
            </table> </fieldset> </form> 
@{ ViewBag.Title = "View Articles"; Layout = "~/Views/Shared/_Layout.cshtml";
            } <h2>@ViewBag.Message</h2> <header> <h3>Article Galary</h3>
            </header> <table> @using (Html.BeginForm("SearchIndex","Article",FormMethod.Get)){
            <tr><td> Title: @Html.TextBox("SearchText")</td> <td><input
            type="submit" value="Search" style ="height:26px;width:auto" /></td></tr>
            } </table> <br /> <table class="tablecss"> @foreach (var article
            in Model) { <tr class="odd"> <td> @Html.ActionLink("Edit", "EditArticle",
            new { id = article.ArticleId }) | @Html.ActionLink("Details", "ViewArticleDetail",
            new { id = article.ArticleId }) | @Html.ActionLink("Delete", "DeleteArticle", new
            { id = article.ArticleId }) <img src="../../Images/Photo/shabir.jpg" alt="" width="42px"
            height="42px"/> </td> <td><b>Published date:</b> @article.ArticlePubsDate
            <br /> <b>Title:</b><a href="@article.ArticleURL">@article.ArticleTitle</a><br
            /> <b>Summary:</b><i>@article.ArticleSummary </i> <b
            style ="color:Orange">@Html.ActionLink("Read more", "ViewArticleDetail", new
            { id = article.ArticleId })>></b> </td> </tr> 
@model Faith.MVC.DAL.Article @{ ViewBag.Title = "ViewArticleDetail";
            Layout = "~/Views/Shared/_Layout.cshtml"; } <div class="page"> <div class="maincontent">
            <div class="article"> <div id="panSummary" class="summarybox"> <ul>
            <li>Av rating:<img id="imgRating1" alt="" src="../../Images/icon_plain_3stars.gif"
            style="height:13px;width:70px;border-width:0px;"/></li> <li>Total
            votes: 135</li> <li>Total comments: 29</li> </ul> <ul>
            <li><img id="imgEmail" alt="" src="../../Images/icon_email_13x11.gif" style="height:11px;
            <a id="lnkEmail" href="">send to a friend</a></li> <li><img
            id="imgPrint" alt="" src="../../Images/icon_print_13x11.gif" style="height:11px;width:14px;border-
            <a id="lnkPrint" href="" target="_blank">printer friendly version</a></li>
            </ul><ul><li> <img alt="" id="imgDownload" alt="" src="../../images/icon_code_14x11.gif"
            style="height:11px;width:14px;border-width:0px;"/> Downloads <ul> <li><a
            id="Relatedarticles_lnkLink" href=""></a></li> </ul></li>
            </ul> </div> <img id="imgAuthor" class="authorpicture" align="left"
            src="../../Images/Photo/shabir.jpg" alt="shabirhakim" style="border-width:0px;"/>
            <div class="articletitle">@Model.ArticleTitle</div> <div class="date">@Model.ArticlePubsDate</div>
            <div class="author">by <a id="ctl00_MainContent_lnkAuthor" rel="author"
            <div class="clear"/> <h3>Introdcution</h3><br /> <div
            class="articleintro"> @Model.ArticleIntroduction </div> <hr /> <h3>Body</h3><br
            /> <div class="articledetail"> @Model.ArticleBody </div> <h3>Summary</h3><br
            /> @Model.ArticleSummary <br /> <br /> <div class="authorpanel"
            > <img id="imgAuthor" class="authorpicture" src="../../Images/Photo/shabir.jpg"
            alt="shabirhakim" align="left" style="border-width:0px;"/> <p><strong>Author
            profile:</strong> <a id="Author1_lnkName" href="#">shabirhakim</a></p>
            <p>shabirhakim is a .NET development instructor which focuses on using XML,
            ADO.NET and Web Services in Microsoft’s .NET platform.</p> <p><a
            id="Author1_lnkSearch" href="">Search for other articles by shabirhakim</a></p>
            <div class="clear"></div></div> </div> <div id="panToRate"
            class="rating"> <h3>   Rate this article:</h3> <br/>
            <table border="0" > <tbody><tr> <td><input id="radRating1"
            type="radio" name="radRating" value="radRating1"/><br/>Poor</td>
            <td><input id="radRating2" type="radio" name="radRating" value="radRating2"/><br/>OK</td>
            <td><input id="radRating3" type="radio" name="radRating" value="radRating3"/><br/>Good</td>
            <td><input id="radRating4" type="radio" name="radRating" value="radRating4"/><br/>Great</td>
            <td><input id="radRating5" type="radio" name="radRating" value="radRating5"/><br/>Must
            read</td> <td> <input type="button" name="btnRateArticle" id="btnRateArticle"
            value="Rate" /> </td></tr> </tbody></table> </div>
            </div> </div> 
Understanding MVC Conventions
There are two kinds of conventions in an MVC project. The first kind is really just suggestions as to how you might like to structure your project. For example, it is conventional to put your JavaScript files in the Scripts folder. This is where other MVC developers would expect to find them, and where Visual Studio puts the initial JavaScript files for a new MVC project. But you are free to rename the Scripts folder, or remove it entirely and put your scripts anywhere you like. That would not prevent the MVC Framework from running your application.The other kind of convention arises from the principle of convention over configuration, which was one of the main selling points that made Ruby on Rails so popular. Convention over configuration means that you don’t need to explicitly configure associations between controllers and their views, for example. You just follow a certain naming convention for your files, and everything just works. There is less flexibility in changing your project structure when dealing with this kind of convention. The following sections explain the conventions that are used in place of configuration.

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  :
  1. NHibernate
  2. Entity Framework
  3. LINQ to SQL

Deciding Between MVC and Web Forms

Problem:  Organisations which are  using  web forms from several years. Suddenly shifting  from webfarm to MVC will be bit tough and hasty decision because  MVC has got steep learning curve and complexity  in Solution architecturing. I believe organisations  need help deciding whether to stick with Web Forms or dive into MVC. If MVC is not yet a standard development framework in your organization, you may need to justify this design decision to management or an enterprise architecture team.
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.

  1. LINQ to SQL supports a wide breadth of abstractions
  2. LINQ to SQL support domain Model
  3. Linq to SQL is only for SQL
  4. LINQ to SQL is simple to use
  5. LINQ to SQL is used for rapid development.
  6. LINQ to SQL class uses the mapping only for the single table
  7. 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.
  1. Entity framework supports a high level of abstraction.
  2. Entity framework support conceptual data mode.
  3. Entity Framework will have ability to target different database engines in addition to Microsoft SQL Server.
  4. Entity framework is complex to use.
  5. Entity framework is slower development but has more capabilities.
  6. Entity framework map a single class to multiple tables
  7. Entity framework generate the three xml files csdl, msl and ssdl. 
Conclusion :
.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. :
  1. Seperating Model and DataAccess from Entity Model
  2. Applying Validation Using the ASP.NET MVC 4
  3. ASP.NET MVC Defining an application architecture:
  4. ASP.NET Application Development Using MVC
  5. How do architect an ASP.Net MVC app with EF?
  6. Using T4 to Generate POCO Classes
Thus far we have seen an overview of the entire ASP.NET MVC Application, and should now have a feel for the huge number of opportunities available to extend and customize how the framework behaves. We've also seen that not all extensibility hooks are created equal, and there are some which are more useful than others. Now that we're all on the same page, the next article will cover how to Seperating Model and DataAccess from Entity Model .
Separating Model from  ADO.NET Entity Data Model
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 below

Here you see list of Projects(layers) to the solution:

FaithModel– This layer will contain the POCO objects
Data Access Layer – This layer will interact with the database and will contain our Entity Framework file FaithDataLayer in my case
Business Access Layer – This layer calls the data layer and implements business rules(FaithBusinessLayer) in my case
Service Layer – This layer contains the actual WCF or Other service that can be accessed by external websites  (FaithServiceLayer) in my case
Web Layer – 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 below

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
  1.  Select "Generate From Database" on the "Choose Model Contents" page.
  2.  Click Next
  3. 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
  4. Click on Test Connection, if the popup says "Test connection succeeded" then click on the "OK" button
  5. Click on the radio button labeled "Yes, include the sensitive data in the connection string" (this can be encrypted later if you wish)
  6. Click the check box labeled "Save entity connection settings in App.Config as" and then give proper connection a name
  7. Click Next
  8. Select all the database objects that you want to include in the Entity Framework (Mostly database tables)
  9. Again give name for the Model Namespace  as per naming convention
  10. Click "Finish" to Wrap up
Finally our Entity Framework Model is created, But if you will observe whole model is in FaithDataLayer.Now our job is to take the Model out of this layer and push it to separate/independent layer namely FaithModel. Once you are done, your Entity Framework Model should look something like this:

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: "" and "". 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 to cut and paste the name ( 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( that is now in the FaithModel project. Just open try to find  line of code that reads something like this:
string inputFile = @"Fmodel.edmx";
And change it to a path where it can find the Entity Framework model over in the FaithDataLayer  project, like so:
string inputFile = @"..\FaithDataLayer\FModel.edmx";
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... 

1 comment:


Introduction A website is a collection of Web pages, images, videos or other digital assets that is hosted on...