13. ADO.NET Entity Framework

About this Tutorial

Objectives

Delegates will learn to develop applications using C# 4.5. After completing this course, delegates will be able to:

  • Use Visual Studio 2012 effectively
  • Create commercial C# Web Applications
  • Develop multi-threaded applications, Use WCF and LINQ

Audience

This course has been designed primarily for programmers new to the .Net development platform. Delegates experience solely in Windows application development or earlier versions of C# will also find the content beneficial.

Prerequisites

No previous experience in C# programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.

Download Solutions

HTML tutorial


Overview

  1. What is the Entity Framework?
    • An Object-Relational Mapping API.
    • Allows you to map database tables to classes, using Visual Studio wizards.
    • These classes are known as “entity classes”.
  2. Entity Data Models:
    • To use the Entity Framework in your application:
      • Add an Entity Data Model to your application.
      • Specify the tables, views, stored procedures to map.
    • An entity data model comprises three categories of mapping metadata:
      • Conceptual model – Defines entity classes / relationships.
      • Physical model – Database storage details.
      • Logical model – Maps entity classes / relationships to tables / FKs.
  3. Using Entities:
    • Your application can manipulate data in memory as entity objects:
      • Load database data into entities.
      • Create, modify, and delete entities.
      • Then synchronise entities back to the database.
    • Entities are managed by “Object Services”:
      • Monitors client-side changes to entities.
      • Manages relationships between entities.
      • Allows you to save changes without writing any SQL.
  4. Querying Entities:
    • The usual way to query entities is by using LINQ to Entities:
      • Uses familiar LINQ operators and techniques.
    • You can also use Entity SQL:
      • An object-oriented version of SQL.
      • Not as commonly used as LINQ to Entities.

Estimated Time – 1 Hour

Not what you are looking? Try the next tutorial – Overview of WPF

Lab 1: Creating a Simple Entity Data Model

Lab 1: Creating a Simple Entity Data Model
  1. In this section we’ll see how to create a simple entity data model – See the SimpleDemo example in the solution that can be downloaded from the top of the page.
  2. The entity data model will map the following database table – In the CarsDatabase database, see the Cars table (To create db, see readme.txt inside the soltuion).
    DataBase
    Database Table for Cars
  1. Open Visual Studio 2013 – Select New Project and using the C# language select Data>ADO.NET Entity Data Model.
    CarDataStart
  2. In the Choose Model Contents screen, choose one of the available options:
    • Generate from Database – Generates an EDM from an
      existing database.
    • Empty model – Creates an empty EDM so you can reverse-engineer
      the database from the EDM.
    • For this example we will be using the first version of generating from a database.
      ModelWizard
  3. Choose Your Data Connection screen – Choose an existing connection, or specify a new one. The connection string references 3 metadata files and will contain mapping info at run time –
    DataConnection
  4. Now you need to choose your database objects – Choose tables, views, and stored procedures to map
    DatabaseObjectsandsettings
  5. Visual Studio generates an .edmx file and displays it in the Designer
    EDMX
  6. To use the Entity Data Model Browser – Select the following menu item: View>Other Windows>Entity Data Model Browser. This is what should be shown:
    • The CarsDatabaseModel is a conceptual model with the entity types and the association between them.
    • The CarsDatabaseModel.Store is a physical model with physical storage information.
      EntityModelBrowser
  7. Reshaping the Entity Model:
    • You can change the name
      of your entity type
      – Select the entity type in the
      Model Browser window and change its name in the
      Properties window
      CarDBVeichle
    • You can also change property
      names
      in the entity by selecting a property in the
      Model Browser window and changing its name in the
      Properties window

      CarDBManafac
  8. Viewing the Generated Entity Classes:
    • To view the generated entity classes:
      • Expand CarsDatabase.edmx.
      • Then expand CarsDatabase.tt.
    • Contains entity classes, e.g. Vehicle:
  9. Viewing the Generated Context Class:
    • To view the generated context class:
      • Expand CarsDatabase.edmx.
      • Then expand CarsDatabase.Context.tt.
    • Contains a context class:
      • Inherits from DbContext.
      • Has DbSet properties, e.g. DbSet<Vehicle>.
  10. Viewing the Generated Mapping Files – When you build the project, three XML mapping files are created:
    • See obj\Debug\edmxResourcesToEmbed folder.
    • Contain the three categories of mapping info.
    • Automatically embedded as resources into .exe file.
    • .csdl = Conceptual model; .msl = Logical mapping model; .ssdl = Physical storage model.
    • Mapping Files

Lab 2: Using Entities in an Application

Lab 2: Using Entities in an Application

Overview

  1. In this section we’ll see how to manage entities in an application:
    • Load entities from a database.
    • Create new entities in memory.
    • Modify existing entities.
    • Delete existing entities.
  2. The Role of the DbContext Class:
    • The DbContext class plays a key role – Our DbContext subclass is CarsDatabaseEntities.
    • DbContext is a LINQ data source – So you can use it in your LINQ queries, it also has a SaveChanges() method, to save pending (in-memory) changes to the database.
    • DbContext maintains sets of entities – Via DbSet properties, such as Vehicles; allows you to access these entities in your code.
Lab
  1. Querying Entities – This example shows how to query entities in the database that should be in program.cs for this example –
    private static void DisplayAllVehicles()
    {
     using (CarsDatabaseEntities context = new CarsDatabaseEntities())
     {
      foreach (Vehicle v in context.Vehicles)
      Console.WriteLine(v);
     }
    }
  2. View code file.
  3. Adding Entities – This example shows how to add an entity. This will be in program.cs for this example –
    private static void AddVehicle()
    {
     using (CarsDatabaseEntities context = new CarsDatabaseEntities())
     {
      try
      {
       context.Vehicles.Add(new Vehicle
       {
       ...
       context.SaveChanges();
      }
      catch (Exception ex)
      ...
     }
    }
  4. View code file.
  5. Deleting Entities – This example shows how to delete an entity –
    private static void DeleteVehicle()
    {
     Console.Write("Enter ID of vehicle to delete: ");
     int id = int.Parse(Console.ReadLine());
     using (CarsDatabaseEntities context = new CarsDatabaseEntities())
     ...
      Vehicle vehicleToDelete = (from v in context.Vehicles ...
      if (vehicleToDelete != null)
      {
       Console.Write("Are you sure you want to delete: {0}? ", vehicleToDelete);
       if (Console.ReadLine().ToUpper()[0] == 'Y')
       ...
      }
     }
    }
  6. View code file.
  7. Modifying Entities – This example shows how to modify an entity –
    private static void ChangeOwner()
    {
     Console.Write("Enter ID of vehicle: ");
     int id = int.Parse(Console.ReadLine());
     Console.Write("Enter new owner: ");
     string newOwner = Console.ReadLine();
     using (CarsDatabaseEntities context = new CarsDatabaseEntities())
     {
      ...
      Vehicle vehicleToChangeOwner = (from v in context.Vehicles ...
      if (vehicleToChangeOwner != null)
      ...
     }
    }
  8. View code file.
  9. Additional Techniques:
    • You can select particular entity fields –
      var vehicleManufacturers = from v in context.Vehicles
                    select v.Manufacturer;
    • You can select projections
      var vehicleSummaries = from v in context.Vehicles
                  select new { v.Reg, v.Manufacturer };
    • You can invoke LINQ extension methods
      var countWalesCars = (from v in context.Vehicles
                 where v.Reg.StartsWith("C")
                 select v.CarID).Count();
  10. Using the Entity Client API:
    • The EF includes an “entity client API” – This is the magic that translates database data to entities in memory.
    • Normally you don’t bother using the entity client API in your own code:
      • But you can if you like.
      • E.g. you can use EntityDataReader to read entities using familiar a “data reader” approach.
      • Used in conjunction with Entity SQL.
    • For example –
      private static void ProcessVehiclesUsingEntityDataReader()
      {
       // Make a connection object, based on our *.config file.
       using (EntityConnection cn = new EntityConnection("name=CarsDatabaseEntities"))
       {
        cn.Open();
        // Now build an Entity SQL query.
        string query = "SELECT VALUE vehicle FROM CarsDatabaseEntities.Vehicles AS vehicle";
        // Create a command object.
        using (EntityCommand cmd = cn.CreateCommand())
        ...
      }
    • View code file.

Lab 3: Creating a Full Entity Data Model

Lab 3: Creating a Full Entity Data Model

Overview

  1. In this section we’ll create a full entity data model:
    • See the FullDemo solution for this lab.
    • One-to-many relationship between Cars and Extras –
      OneToMany
    • Plus a stored procedure
      StoredProcedure
Lab
  1. Viewing the Entity Data Model:
    • Note the following points in the entity data model:
      • The Car and Extra entity types.
      • The association between the Extras and Cars tables.
      • The navigation properties that allow you to navigate between a car and its extras, and vice versa.
        ViewEntityDataModel
  2. Stored Procedures – If you’ve included stored procedures in your entity model, they are automatically mapped to functions in your entity model –
    StoredProcedureModelB
  3. Navigating Relationships:
    • To navigate a one-to-many relationship – E.g. for a given car, get all its extras –
      private static void DisplayExtrasForCar(int carID)
      {
       using (CarsDatabaseEntities context = new CarsDatabaseEntities())
       {
        var extras = from e in context.Extras
               where e.CarID == carID
               select e;
        foreach (var e in extras)
        {
         Console.WriteLine(e);
        }
       }
      }
    • View code file.
    • To navigate a many-to-one relationship – E.g. for a given extra, get the car it belongs to –
      private static void DisplayCarsThatOwnExtras(IEnumerable<Extra> extras)
      {
       using (CarsDatabaseEntities context = new CarsDatabaseEntities())
       {
        foreach (Extra extra in extras)
        {
         var theCar = (from c in context.Cars
                where c.CarID == extra.CarID
                select c).First();
         Console.WriteLine("{0}, registration {1}, owner {2}, has {3} extras.",
                   theCar.Make,
                   ...
        }
       }
      }
    • View code file.
    • To add an entity in a many-to-one relationship – E.g. add an extra to a car –
      private static void AddEjectorSeatToCar(int carID)
      {
       using (CarsDatabaseEntities context = new CarsDatabaseEntities())
       {
        var theCar = (from c in context.Cars
               where c.CarID == carID
               select c).First();
        theCar.Extras.Add(new Extra { Description = "Ejector seat", Cost = 40000 });
        context.SaveChanges();
       }
      }
    • View code file.
  4. To invoke a stored procedure:
    • Call the mapped function in the entity model.
    • Use ObjectParameter to specify types for in-out params, and to access values after execution.
      private static void AddEjectorSeatToCar(int carID)
      {
       using (CarsDatabaseEntities context = new CarsDatabaseEntities())
       {
        var theCar = (from c in context.Cars
               where c.CarID == carID
               select c).First();
        theCar.Extras.Add(new Extra { Description = "Ejector seat", Cost = 40000 });
        context.SaveChanges();
       }
      }
    • View code file.

 

Well done. You have completed the tutorial in the C# course. The next tutorial is

14. Overview of WPF


Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top