Thursday, December 12, 2013

MVVM vs MVP vs MVC: The differences explained


MVVM vs MVP vs MVC: The differences explained

May 6, 2011 by     18 Comments    Posted under: Linked In, Software Development
For the consicise explanation, see MVVM vs MVP vs MVC: The concise explanation

Those who know me know that I have a passion for software architecture and after developing projects using Model-View-ViewModel (MVVM), Model-View-Presenter (MVP), and Model-View-Controller (MVC),  I finally feel qualified to talk about the differences between these architectures.  The goal of this article is to clearly explain the differences between these 3 architectures.

Common Elements

First, the let’s define common elements.  All 3 of the architectures are designed to separate the view from the model.

Model

  • Domain entities & functionality
  • Knows only about itself and not about views, controllers, etc.
  • For some projects, it is simply a database and a simple DAO
  • For some projects, it could be a database/file system, a set of entities, and a number of classes/libraries that provide additional logic to the entities (such as performing calculations, managing state, etc)
Implementation: Create classes that describe your domain and handle functionality.  You probably should end up with a set of  domain objects and a set of classes that manipulate those objects.

View

  • Code that handles the display
  • Note that view related code in the codebehind is allowed (see final notes at the bottom for details)
Implementation:  HTML, WPF, WindowsForms, views created programmatically – basically code that deals with display only.

Differences between Presenters, ViewModels and Controllers

This is the tricky part.  Some things that Controllers, Presenters, and ViewModels have in common are:
  • Thin layers
  • They communicate with the model and the view
The features of each.

Presenter (Example: WinForms)

  • 2 way communication with the view
  • View Communication: The view communicates with the presenter by directly calling functions on an instance of the presenter.  The presenter communicates with the view by talking to an interface implemented by the view.
  • There is a single presenter for each view
Implementation:
  • Every view’s codebehind implements some sort of IView interface.  This interface has functions like displayErrorMessage(message:String), showCustomers(customers:IList<Customer>), etc.  When a function like showCustomers is called in the view, the appropriate items passed are added to the display.  The presenter corresponding to the view has a reference to this interface which is passed via the constructor.
  • In the view’s codebehind, an instance of the presenter is referenced.  It may be instantiated in the code behind or somewhere else.  Events are forwarded to the presenter  through the codebehind.  The view never passes view related code (such as controls, control event objects, etc) to the presenter.
A code example is shown below.
//the view interface that the presenter interacts with
public interface IUserView
{
    void ShowUser(User user);
    ...
}
 
//the view code behind
public partial class UserForm : Form, IUserView
{
    UserPresenter _presenter;
    public UserForm()
    {
        _presenter = new UserPresenter(this);
        InitializeComponent();
    }
 
    private void SaveUser_Click(object sender, EventArgs e)
    {
        //get user from form elements
        User user = ...;
        _presenter.SaveUser(user);
    }
 
    ...
}
 
public class UserPresenter
{
    IUserView _view;
    public UserPresenter(IUserView view){
        _view = view;
    }
 
    public void SaveUser(User user)
    {
 ...
    }
    ...
}

ViewModel (Example: WPF, Knockoutjs)

  • 2 way communication with the view
  • The ViewModel represents the view.  This means that fields in a view model usually match up more closely with the view than with the model.
  • View Communication:  There is no IView reference in the ViewModel.  Instead, the view binds directly to the ViewModel.  Because of the binding, changes in the view are automatically reflected in the ViewModel and changes in the ViewModel are automatically reflected in the view.
  • There is a single ViewModel for each view
Implementation:
  • The view’s datacontext is set to the ViewModel.  The controls in the view are bound to various members of the ViewModel.
  • Exposed ViewModel proproperties implement some sort of observable interface that can be used to automatically update the view (With WPF this is INotifyPropertyChanged; with knockoutjs this is done with the functions ko.observable() and ko.observrableCollection())

Controller (Example: ASP.NET MVC Website)

  • The controller determines which view is displayed
  • Events in the view trigger actions that the controller can use to modify the model or choose the next view.
  • There could be multiple views for each controller
  • View Communication:
    • The controller has a method that determines which view gets displayed
    • The view sends input events to the controller via a callback or registered handler.  In the case of a website, the view sends events to the controller via a url that gets routed to the appropriate controller and controller method.
    • The view receives updates directly from the model without having to go through the controller.
      • Note: In practice, I don’t think this particular feature of MVC is employed as often today as it was in the past.  Today, I think developers are opting for MVVM (or MVP) over MVC in most situations where this feature of MVC would have been used.  Websites are a situation where I think MVC is still a very practical solution.  However, the view is always disconnected from the server model and can only receive updates with a request that gets routed through the controller.  The view is not able to receive updates directly from the model.
Implementation (for web):
  • A class is required to interpret incoming requests and direct them to the appropriate controller.  This can be done by just parsing the url.  Asp.net MVC does it for you.
  • If required, the controller updates the model based on the request.
  • If required, the controller chooses the next view based on the request.  This means the controller needs to have access to some class that can be used to display the appropriate view.  Asp.net MVC provides a function to do this that is available in all controllers.  You just need to pass the appropriate view name and data model.
MVVM and MVP implementation seem pretty straightforward but MVC can be a little confusing.  The diagram below from Microsoft’s Smart Client Factory documentation does a great job at showing MVC communication.  Note that the controller chooses the view (ASP.NET MVC) which is not shown in this diagram.  MVVM interactions will look identical to MVP (replace Presenter with ViewModel).  The difference is that with MVP, those interactions are handled programmatically while with MVVM, they will be handled automatically by the data bindings.

General rules for when to use which?

MVP
  • Use in situations where binding via a datacontext is not possible.
  • Windows Forms is a perfect example of this.  In order to separate the view from the model, a presenter is needed.  Since the view cannot directly bind to the presenter, information must be passed to it view an interface (IView).
MVVM
  • Use in situations where binding via a datacontext is possible.  Why?  The various IView interfaces for each view are removed which means less code to maintain.
  • Some examples where MVVM is possible include WPF and javascript projects using Knockout.
MVC
  • Use in situations where the connection between the view and the rest of the program is not always available (and you can’t effectively employ MVVM or MVP).
  • This clearly describes the situation where a web API is separated from the data sent to the client browsers.  Microsoft’s ASP.NET MVC is a great tool for managing such situations and provides a very clear MVC framework.

Final notes

  • Don’t get stuck on semantics.  Many times, one of your systems will not be purely MVP or MVVM or MVC.  Don’t worry about it.  Your goal is not to make an MVP, MVVM, or MVC system.  Your goal is to separate the view, the model, and the logic that governs both of them. It doesn’t matter if your view binds to your ‘Presenter’, or if you have a pure Presenter mixed in with a bunch of ViewModels.  The goal of a maintainable project is still achieved.
  • Some evangelists will say that your ViewModels (and Presenters) must not make your model entities directly available for binding to the view.   There are definitely situations where this is a bad thing.  However, don’t avoid this for the sake of avoiding it.  Otherwise, you will have to constantly be copying data between your model and ViewModel.  Usually this is a pointless waste of time that results in much more code to maintain.
  • In line with the last point, if using WPF it makes sense to implement INotifyPropertyChanged in your model entities.  Yes, this does break POCO but when considering that INotifyPropertyChanged adds a lot of functionality with very little maintenance overhead , it is an easy decision to make.
  • Don’t worry about “bending the rules” a bit so long as the main goal of a maintainable program is achieved
  • Views
    • When there is markup available for creating views (Xaml, HTML, etc), some evangelists may try to convince developers that views must be written entirely in markup with no code behind.  However, there are perfectly acceptable reasons to use the code behind in a view if it is dealing with view related logic.  In fact, it is the ideal way to keep view code out of your controllers, view models, and  presenters.  Examples of situations where you might use the code behind include:
      • Formatting a display field
      • Showing only certain details depending on state
      • Managing view animations
    • Examples of code that should not be in the view
      • Sending an entity to the database to be saved
      • Business logic

Understanding Basics of UI Design Pattern MVC, MVP and MVVM

Understanding Basics of UI Design Pattern MVC, MVP and MVVM

By , 20 Jul 2011



Introduction

This is my first article and I hope you will like it. After reading this article, you will have a good understanding about "Why we need UI design pattern for our application?" and "What are basic differences between different UI patterns (MVC, MVP, MVVP)?”.
In traditional UI development - developer used to create a View using window or usercontrol or page and then write all logical code (Event handling, initialization and data model, etc.) in code behind and hence they were basically making code as a part of view definition class itself. This approach increased the size of my view class and created a very strong dependency between my UI and data binding logic and business operations. In this situation, no two developers can work simultaneously on the same view and also one developer's changes might break the other code. So everything is in one place is always a bad idea for maintainability, extendibility and testability prospective. So if you look at the big picture, you can feel that all these problems exist because there is a very tight coupling between the following items.
  1. View (UI)
  2. Model (Data displayed in UI)
  3. Glue code (Event handling, binding, business logic)
Definition of Glue code is different in each pattern. Although view and model is used with the same definition in all patterns.
In case of MVC it is controller. In case of MVP it is presenter. In case of MVVM it is view model.
If you look at the first two characters in all the above patterns, it remain same i.e. stands for model and view. All these patterns are different but have a common objective that is “Separation of Duties"
In order to understand the entire article, I request readers to first understand the above entity. A fair idea about these will help you to understand this article. If you ever worked on UI module, you can easily relate these entities with your application.
MVC (model view controller), MVP (model view presenter) and MVVM (model view view model) patterns allow us to develop applications with loss coupling and separation of concern which in turn improve testability, maintainability and extendibility with minimum effort.
MVVM pattern is a one of the best solutions to handle such problems for WPF and Silverlight application. During this article, I will compare MVC, MVP and MVVM at the definition level.

MVP & MVC

Before we dig into MVVM, let’s start with some history: There were already many popular design patterns available to make UI development easy and fast. For example, MVP (model view presenter) pattern is one of the very popular patterns among other design patterns available in the market. MVP is a variation of MVC pattern which is being used for so many decades. Simple definition of MVP is that it contains three components: Model, View and presenter. So view is nothing but a UI which displays on the screen for user, the data it displays is the model, and the Presenter hooks the two together (View and model).
View,Model,Presenter,Model The view relies on a Presenter to populate it with model data, react to user input, and provide input validation. For example, if user clicks on save button, corresponding handling is not in code behind, it’s now in presenter. If you wanted to study it in detail, here is the MSDN link.
In the MVC, the Controller is responsible for determining which View is displayed in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View basically calls to a Controller along with an action. In web application, each action is a call to a URL and for each such call there is a controller available in the application who respond to such call. Once that Controller has completed its processing, it will return the correct View.
In case of MVP, view binds to the Model directly through data binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation. It means while implementing this pattern, we have to write some code in code behind of view in order delegate (register) to the presenter. However, in case of MVC, a view does not directly bind to the Model. The view simply renders, and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. Since controller itself returns view while responding to URL action, there is no need to write any code in view code behind file.

MVC Steps

Step 1: Incoming request directed to Controller.
View,Model,Presenter,Model
Step 2: Controller processes request and forms a data Model.
View,Model,Presenter,Model
Step 3: Model is passed to View.
View,Model,Presenter,Model
Step 4: View transforms Model into appropriate output format.
View,Model,Presenter,Model
Step 5: Response is rendered.
View,Model,Presenter,Model
So now you have basic understanding of MVC and MVP. Let’s move to MVVM.

MVVM (Model View ViewModel)

The MVVM pattern includes three key parts:
  1. Model (Business rule, data access, model classes)
  2. View (User interface (XAML))
  3. ViewModel (Agent or middle man between view and model)
View,Model,ViewModel
Model and View work just like MVC and “ViewModel” is the model of the View.
  • ViewModel acts as an interface between model and View.
  • ViewModel provides data binding between View and model data.
  • ViewModel handles all UI actions by using command.
In MVVM, ViewModel does not need a reference to a view. The view binds its control value to properties on a ViewModel, which, in turn, exposes data contained in model objects. In simple words, TextBox text property is bound with name property in ViewModel.
In View:
<TextBlock Text="{Binding Name}"/> 
In ViewModel:
public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                this.name = value;
                this.OnPropertyChanged("Name");
            }
        }
ViewModel reference is set to a DataContext of View in order to set view data binding (glue between view and ViewModel model).
Code behind code of View:
public IViewModel Model
        {
            get
            {
                return this.DataContext as IViewModel;
            }
            set
            {
                this.DataContext = value;
            }
        }
If property values in the ViewModel change, those new values automatically propagate to the view via data binding and via notification. When the user performs some action in the view for example clicking on save button, a command on the ViewModel executes to perform the requested action. In this process, it’s the ViewModel which modifies model data, View never modifies it. The view classes have no idea that the model classes exist, while the ViewModel and model are unaware of the view. In fact, the model doesn’t have any idea about ViewModel and view exists.

Where to Use What in the .NET World

  • Model-View-Controller (MVC) pattern
    • ASP.NET MVC 4 Link
    • Disconnected Web Based Applications
  • Model-View-Presenter (MVP) pattern
    • Web Forms/SharePoint, Windows Forms
  • Model-View-ViewModel (MVVM) pattern
    • Silverlight, WPF Link
    • Data binding

Sources and References

Saturday, December 7, 2013

Introducing LINQ to Relational Data

Introducing LINQ to Relational Data

123 out of 162 rated this helpful Rate this topic

Microsoft Data Platform Development Technical Article
Writers: Elisa Flasko, Microsoft Corporation
Published: January 2008
Level: 100/200
Applies To:
LINQ to SQL
LINQ to Entities
ADO.NET Entity Framework
You can also download a Microsoft Word version of this article.
Summary: This article introduces two implementations of LINQ, LINQ to SQL and LINQ to Entities, and the key scenarios for which each was designed. (19 printed pages)

Introducing LINQ to Relational Data

With the combined launch of Visual Studio 2008, SQL Server 2008, and Windows Server 2008, Microsoft is introducing five implementations of .NET Language Integrated Query (LINQ).
Of these five implementations, two specifically target access to relational databases: LINQ to SQL and LINQ to Entities. This white paper introduces these two technologies and the scenarios in which each can best be used.
Microsoft Language Integrated Query (LINQ) offers developers a new way to query data using strongly-typed queries and strongly-typed results, common across a number of disparate data types including relational databases, .NET objects, and XML. By using strongly-typed queries and results, LINQ improves developer productivity with the benefits of IntelliSense and compile-time error checking. 
LINQ to SQL, released with the Visual Studio 2008, is designed to provide strongly-typed LINQ access for rapidly developed applications across the Microsoft SQL Server family of databases.
LINQ to Entities, to be released in an update to Visual Studio 2008 in the first half of 2008, is designed to provide strongly-typed LINQ access for applications requiring a more flexible Object Relational mapping, across Microsoft SQL Server and third-party databases. 

What Is LINQ to SQL?

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.
Figures 1 & 2 combined with the code snippet below demonstrate a simple LINQ to SQL scenario. Figure 1 shows the LINQ to SQL mapping, and Figure 2 shows the associated database diagram, using the Northwind database.
Figure 1. Database diagram for a subset of the Northwind database.
Figure 2. LINQ to SQL mapping diagram for a simple scenario using a subset of the Northwind database and the associated database diagram. Notice the use of an intermediary table to map the many-to-many relationship between Employees and Territories.
This code snippet shows a simple LINQ query against the Northwind database to retrieve all customers whose address is in London.
NorthwindDataContext db = new NorthwindDataContext();
var customers = from c in db.Customers
                where c.City == "London"
                select c;
Listing 1. Simple LINQ to SQL query
LINQ to SQL has been architected with simplicity and developer productivity in mind. APIs have been designed to “just work” for common application scenarios. Examples of this design include the ability to replace unfriendly database naming conventions with friendly names, to map SQL schema objects directly to classes in the application, to implicitly load data that has been requested but has not previously been loaded into memory, and the use of common naming conventions and partial methods to provide custom business or update logic.
The ability to replace unfriendly database naming conventions with more developer friendly names provides benefit that is pretty self explanatory, making it easier to understand the structure and meaning of data as the application is developed. These changes can be done using the LINQ to SQL designer in Visual Studio 2008, by double clicking on the entity object name, as seen in Figure 3 below.

Figure 3. Changing the name of an entity object in LINQ to SQL.
As mentioned above, LINQ to SQL targets scenarios where the database closely resembles the application object model that is desired. Given this target scenario, the mapping between the SQL schema and classes in the application is a direct 1-1 mapping, meaning that a table or view being accessed from the database maps to a single class in the application, and a column being accessed maps to a property on the associated class.
By default, LINQ to SQL enables deferred loading. This means that if, for example, a query retrieves Customer data, it does not automatically pull the associated Order information into memory. When the data is requested however, LINQ to SQL uses its implicit loading capability to retrieve the data that has been requested but has not previously been loaded into memory. In Listing 1 we queried the database for all customers with an address based in London. While iterating through the resulting list of customers we would like to access the list of Orders that each customer has placed. Looking back to the original query in Listing 1, we notice that we did not retrieve any information about Orders; we simply retrieved information included in the Customer object. In Listing 2, we continue from the previous query to iterate through the customers that were returned and print out the total number Orders associated with each customer.
foreach (Customer c in customers)
{
     Console.WriteLine(c.CompanyName + " " + c.Orders.Count);              
}
Listing 2. Implicit loading of Orders data that has been requested but not previously loaded into memory.
In the above example, a separate query is executed to retrieve the Orders for each Customer. If it is known in advance that we need to retrieve the orders for all customers, we can use LoadOptions to request that the associated Orders be retrieved along with the Customers, in a single request.
Beyond the simplicity of the query experience, LINQ to SQL offers additional features to improve the developer experience with regards to application logic. Partial methods, a new language feature of C# and VB in Visual Studio 2008, allow one part of a partial class to define and call methods which are invoked, if implemented in another part of the class. If the method has not been implemented; the entire method call is optimized away during compilation. By using common naming conventions in conjunction with these new partial methods and partial classes, introduced in Visual Studio 2005, LINQ to SQL allows application developers to provide custom business logic when using generated code. Using partial classes allows developers the flexibility to add methods, non-persistent members, etc., to the generated LINQ to SQL object classes. These partial methods can add logic for insert, update, and delete by simply implementing the associated partial method. Similarly, developers can use the same concepts to implement partial methods that hook up eventing in the most common scenarios, for example OnValidate, OnStatusChanging or OnStatusChanged.  Example 3 shows the use of partial methods to implement custom validation on the Customer Phone property as it is changed.
public partial class Customer
{
    partial void OnPhoneChanging(string value)
    {
        Regex phoneNum = new Regex(@"^[2-9]\d{2}-\d{3}-\d{4}$");
        if (phoneNum.IsMatch(value) == false)
            throw new Exception("Please enter a valid Phone Number");
    }
}
Listing 3. Use of partial methods to implement custom validation logic.
Once developers can leverage the query capabilities of LINQ and implement business logic in partial methods, the argument for using persistent objects becomes quite compelling. To round the story out, LINQ to SQL allows people to model inheritance hierarchies in their classes and map them to the database. Inheritance, an important feature of object-oriented programming, does not translate directly into the relational database; therefore, the ability to map inheritance from the application into the database is very important. LINQ to SQL supports one of the most common database inheritance mappings, Table per Hierarchy (TPH), where multiple classes in a hierarchy are mapped to a single table, view, stored procedure, or table valued function using a discriminator column to determine the specific type of each row/instance. In Figure 4, a single Product table in the database, maps the inheritance of DiscontinuedProduct from Product. This two-class hierarchy is mapped directly to the existing Northwind database using the discriminator column “Discontinued”.


Figure 4. Inheritance in LINQ to SQL
Notice that the properties of the inheritance (right-click on the relationship arrow) specify the discriminatory property and the associated discriminator values, while the properties of DiscontinuedProduct specify the base class from which it inherits.
LINQ to SQL has been developed with a minimally intrusive object model, allowing developers to choose whether or not to make use of generated code. Rather, they can create their own classes, which do not need to be derived from any specific base class. This means that you can create classes that inherit from no base class or from a custom base class.
As with any application framework, developers must also have the ability to optimize the solution to best fit their scenario. LINQ to SQL offers a number of opportunities to optimize, including using load options to control database trips and compiled queries to amortize the overhead inherent in SQL generation. By default, LINQ to SQL enables Object Tracking, which controls the automatic change tracking and identity management of objects retrieved from the database. In some scenarios, specifically where you are accessing the data in a read-only manner, you may wish to disable Object Tracking as a performance optimization. The options for specialization of your application behavior is not local to just the API, the LINQ to SQL Designer also allows additional functionality for you to expose stored procedures and/or table valued functions as strongly typed methods on the generated DataContext, and map inserts, updates, and deletes to stored procedures if you choose not to use dynamic SQL.
Developers who are concerned about query performance can leverage the compiled queries capabilities which offer an opportunity to optimize query performance. In many applications you might have code that repeatedly executes the same query, possibly with different argument values. By default, LINQ to SQL parses the language expression each time to build the corresponding SQL statement, regardless of whether that expression has been seen previously. Compiled queries, like that seen in Listing 4, allow LINQ to SQL to avoid reparsing the expression and regenerating the SQL statement for each repeated query.   
var customers = CompiledQuery.Compile(
                    (NorthwindDataContext context,
                     string filterCountry) =>
                        from c in context.Customers
                        where c.Orders.Count > 5
                        select c);

NorthwindDataContext db = new NorthwindDataContext();
           Console.WriteLine("Customers in the USA: ");
foreach (var row in customers(db, "USA"))
{
       Console.WriteLine(row.CompanyName);
}
Console.WriteLine();
Console.WriteLine("Customers in Spain: ");
foreach (var row in customers(db, "Spain"))
{
       Console.WriteLine(row.CompanyName);
}
Listing 4. An example of a simple compiled query, executed twice with varying parameters.

When Do I Use LINQ to SQL?

The primary scenario for using LINQ to SQL is when building applications with a rapid development cycle and a simple one-to-one object to relational mapping against the Microsoft SQL Server family of databases. In other words, when building an application whose object model is structured very similarly to the existing database structure, or when a database for the application does not yet exist and there is no predisposition against creating a database schema that mirrors the object model; you can use LINQ to SQL to map a subset of tables directly to classes, with the required columns from each table represented as properties on the corresponding class. Usually in these scenarios, the database has not and/or will not be heavily normalized.

I want to
LINQ to SQL is applicable
Use an ORM solution and my database is 1:1 with my object model

Use an ORM solution with inheritance hierarchies that are stored in a single table

Use my own plain CLR classes instead of using generated classes or deriving from a base class or implementing an interface

Leverage LINQ as the way I write queries

Use an ORM but I want something that is very performant and where I can optimize performance through stored procedures and compiled queries

Table 1. LINQ to SQL Scenarios

What Is LINQ to Entities?

LINQ to Entities, like LINQ to SQL is a LINQ implementation providing access to relational data, but with some key differences.
LINQ to Entities is, specifically, a part of the ADO.NET Entity Framework which allows LINQ query capabilities. The Entity Framework is the evolution of ADO.NET that allows developers to program in terms of the standard ADO.NET abstraction or in terms of persistent objects (ORM) and is built upon the standard ADO.NET Provider model which allows access to third party databases. The Entity Framework introduces a new set of services around the Entity Data Model (EDM) (a medium for defining domain models for an application). This set of services includes the following:
·         Domain Modeling  Capabilities and the ability to define conceptual, data store agnostic models
·         Object Relational Mapping Capabilities (full CRUD and state management scenarios)
·         Database independent Query Capabilities using LINQ or Entity SQL
More than a simple Object Relational Mapping (ORM) tool, the ADO.NET Entity Framework and LINQ to Entities allow developers to work against a conceptual model with a very flexible mapping and the ability to accommodate a high degree of divergence from the underlying data store. For further discussion of the Entity Framework and EDM, please see the Data Platform Development Center (http://msdn.microsoft.com/data).
Figure 5 below shows a simple LINQ to Entities EDM diagram, using the same subset of the Northwind database seen in Figure 1.

Figure 5. LINQ to Entities mapping diagram corresponding to the Northwind database subset in Figure 1. Notice the directly mapped many-to-many relationship between Employees and Territories without an intermediary table.
In this figure you can see that the object model is not mapped directly, one-to-one, to the database, rather we have bypassed the intermediary table used to represent the many-to-many relationship between Employees and Territories.  Although you can map many-to-many relationships in both LINQ to SQL and LINQ to Entities, LINQ to Entities allows a direct mapping of many-to-many relationships with no intermediary class, while LINQ to SQL requires that an intermediary class map one-to-many to each of the classes that are party to the many-to-many relationship.
Listing 5 below shows the same simple LINQ query used in Listing 1 for LINQ to SQL, used against the Entity Data Model shown in Figure 5. 
using (NorthwindEntities nw = new NorthwindEntities())
{
       var cusotmers = from c in nw.Customers
                       where c.City == "London"
                       select c;
}
Listing 5. Simple LINQ to Entities query
The similarities between the two LINQ implementations for this simple query highlight the benefit of LINQ creating a query language that remains consistent across data stores.
Microsoft designed the ADO.NET Entity Framework, and in turn LINQ to Entities, to enable flexible and more complex mappings, ideal in the scenario where it is not possible or ideal for the object model to match the database schema. The mapping flexibility available with the ADO.NET Entity Framework allows the database and application(s) to evolve separately and makes development against highly normalized databases simpler and easier to understand. When a change is made in the database schema, the application is insulated from the change by the Entity Framework, and there is no requirement to rewrite portions of the application, but rather the mapping files can simply be updated to accommodate the database change. In Figures 6 & 7, a change is made to the database splitting the Employees table to separate personal information that is only accessible to HR and information that is available in the Employee Address Book. If existing applications are not going to make use of these changes we simply need to update the mapping to account for this change.

Figure 6. Database Model for the new modified Northwind database subset. In this modified database, we have split the Employees table into two tables one containing Employee information that is only available to HR and another containing information that is available to all employees in the Employee Address Book. We have also used a different inheritance mapping, Table per Subclass, which we will discuss later.


Figure 7. Entity Data Model Diagram for the modified Northwind database subset shown in Figure 6.
Listing 6 shows a query against a single entity, mapped to multiple tables in the database. The same query directly against the database would require the knowledge that Employee information is split between two tables and a join of those two tables in the query.
using (NorthwindModEntities nw = new NorthwindModEntities())            {
       var q = from e in nw.Employees
               select e;
       foreach (Employees emp in q)
       {
               Console.WriteLine(emp.FirstName + ", " + emp.LastName + ", Hire Date: " + emp.HireDate.ToString());
       }
}
Listing 6. Querying a single Entity mapped to two tables in the database.
As discussed earlier in this article, LINQ to SQL allows one of the most common inheritance scenarios to be mapped, Table per Hierarchy. LINQ to Entities and the ADO.NET Entity Framework also allow the mapping of two other types of inheritance. In addition to Table per Hierarchy (as supported by LINQ to SQL), the Entity Framework supports:
·         The mapping of Table per Concrete Type, a separate table for each class or type in the hierarchy.
·         The mapping of Table per Subclass, a hybrid approach using a shared table for information about the base type and separate tables for information about the derived types seen in Figure 8.  

Figure 8. Mapping Table per Subclass inheritance with the Entity Data Model.
Similar to LINQ to SQL, LINQ to Entities uses partial classes and partial methods to allow update and business logic to be easily added to generated code. Using partial classes and partial methods allows developers the flexibility to add methods, non-persistent members, etc., to the generated Entity Framework object classes, and for the addition of custom logic for insert, update, and delete by simply implementing the associated partial method. Similarly, developers can use the same concepts to implement partial methods that hook up eventing in the most common scenarios, for example OnStatusChanging or OnStatusChanged. Listing 7 shows the use of partial methods to implement custom validation on the Customer Phone property as it is changed.
public partial class Customers
{
       partial void OnPhoneChanging(string value)
       {
            Regex phoneNum = new Regex(@"^[2-9]\d{2}-\d{3}-\d{4}$");
            if (phoneNum.IsMatch(value) == false)
                throw new Exception("Please enter a valid Phone Number");
       }
}
Listing 7. Use of partial methods to implement custom validation logic.
Due to the explicit nature of LINQ to Entities, developers also have the ability to optimize the solution to best fit their scenario. In Listing 2 for LINQ to SQL, when we queried for Customer data, Order information was not automatically pulled into memory, but rather was only pulled into memory only when the Order information was accessed. In LINQ to Entities, the developer has full control over the number of database round trips by explicitly specifying when to load such information from the database. Navigating to associated information that has not yet been retrieved from the database will not cause an additional database trip, but rather will only return the information if it was explicitly requested with the first query or with a new query, as seen in Listing 8.
using (NorthwindModEntities nw = new NorthwindModEntities())
{
   var q = from cus in nw.Customers
           where cus.City == "London"
           select cus;
// Loop through customers and print out orders since January 1, 1998
   foreach (Customers customer in q)
   {
       Console.WriteLine(customer.CompanyName + ": " );
// Note line below to explicitly load all orders for each customer
       customer.Orders.Load();
       foreach (Orders order in customer.Orders.Where(o => o.OrderDate > new DateTime(1998, 1, 1)))
       {
           Console.WriteLine("\t{0},{1}", order.OrderID, order.OrderDate);
       }
   }
   Console.ReadLine();
}
Listing 8. Explicit loading of information to control number of database roundtrips.
Like LINQ to SQL, LINQ to Entities enables Object Tracking by default. In some scenarios, specifically where you are accessing the data in a read-only manner, you may wish to disable Object Tracking as a performance optimization.
LINQ to Entities also provides the ability to expose stored procedures as strongly typed methods on the generated ObjectContext, and map inserts, updates, and deletes to stored procedures if you choose not to use dynamic SQL.

When do I use LINQ to Entities?

The primary scenario targeted by LINQ to Entities is a flexible and more complex mapping scenario, often seen in the enterprise, where the application is accessing data stored in Microsoft SQL Server or other-third party databases.
In other words, the database in these scenarios contains a physical data structure that could be significantly different from what you expect your object model to look like. Often in these scenarios, the database is not owned or controlled by the application developer(s), but rather owned by a DBA or other third party, possibly preventing application developers from making any changes to the database and requiring them to adapt quickly to database changes that they may not have been aware of.

I want to
LINQ to Entities is applicable
Write applications that can target different database engines in addition to Microsoft SQL Server

Define domain models for my application and use these as the basis for my persistence layer.

Use an ORM solution where my classes may be 1:1 with the database or may have a very different structure from the database schema

Use an ORM solution with inheritance hierarchies that may have alternative storage schemes (single table for the hierarchy, single table for each class, single table for all data related to specific type)

Leverage LINQ as the way I write queries and have the query work in a database vendor agnostic manner.

Use an ORM but I want something that is very performant and where I can optimize performance through stored procedures and compiled queries

Table 2. LINQ to Entities Scenarios