Entity Framework Video Content

Embed Size (px)

Citation preview

  • 8/10/2019 Entity Framework Video Content

    1/61

    Part 1 - What is Entity Framework

    What is Entity Framework

    Entity Framework is an ORM framework. ORM stands for Object Relational Mapping.

    What is Object Relational Mapping framework

    Object Relational Mapping framework automatically creates classes based on database tables, and

    the vice versa is also true, that is, it can also automatically generate necessary SQL to create

    database tables based on classes.

    Let's understand what entity framework can provide with an example. Assume we have the

    following 2 tables

    We want to display the above data from both the tables in a webform as shown below.

    To achieve this

    1. We need to create Department and Employee classes

    2. Write ADO.NET code to retrieve data from the database3. Once the data is retrieved we need to create Department and Employee objects and populate

  • 8/10/2019 Entity Framework Video Content

    2/61

    them with data.

    Entity Framework can do all of the above automatically, if we provide it with the database

    schema.

    Installing NuGet Package Manager

    1. From Visual Studio 2010 Tools menu, select Extension Manager

    2. Click on Online Gallery in the Extension Manager window

    3. Search for NuGet

    4. Finally Download NuGet Package Manager and install

    Please note:You must restart visual studio for the changes to take effect.

    Step 1: Create a new "Empty ASP.NET Web Application" with name=Demo.

    Step 2: Installing Entity Framework

    a)Click on Tools - NuGet Package Manager - Manage NuGet Packages for solution

    b)Click on "Online" tab in "Manage NuGet Packages" window

    c)Type "EntityFramework" in the search textbox on the top right hand corner

    d)Finally click on the "Install" button.

  • 8/10/2019 Entity Framework Video Content

    3/61

    At this point Entity Framework version 6.1is installed and a reference to EntityFrameworkassembly is also automatically added.

    Step 3:Create "Departments" and "Employees" tables.

    CreatetableDepartments

    (

    ID intprimarykeyidentity,

    Name nvarchar(50),

    Location nvarchar(50))

    CreatetableEmployees

    (

    ID intprimarykeyidentity,

    FirstName nvarchar(50),

    LastName nvarchar(50),

    Gender nvarchar(50),

    Salary int,

    DepartmentId intforeignkeyreferencesDepartments(Id))

  • 8/10/2019 Entity Framework Video Content

    4/61

    Step 4:Populate the tables created in Step 3, with data

    InsertintoDepartments values ('IT', 'New York')

    InsertintoDepartments values ('HR', 'London')

    InsertintoDepartments values ('Payroll', 'Sydney')

    InsertintoEmployees values ('Mark', 'Hastings', 'Male', 60000, 1)

    InsertintoEmployees values ('Steve', 'Pound', 'Male', 45000, 3)

    InsertintoEmployees values ('Ben', 'Hoskins', 'Male', 70000, 1)

    InsertintoEmployees values ('Philip', 'Hastings', 'Male', 45000, 2)

    InsertintoEmployees values ('Mary', 'Lambeth', 'Female', 30000, 2)

    InsertintoEmployees values ('Valarie', 'Vikings', 'Female', 35000, 3)

    InsertintoEmployees values ('John', 'Stanmore', 'Male', 80000, 1)

    Step 5:Right click on the project in solution explorer and add ADO.NET Entity Data Model.

    Change the name from Model1.edmxto EmployeeModel.edmx

    Step 6:Select "Generate from database"and click "Next"

    Step 7:Choose Your Data Connection

    a)Click on "New Connection" button

    b)Select "Microsoft SQL Server" as Data source, and ".Net Framework Data Provider for SQL

    Server" option from "Data provider" dropdownlist. Click Continue.

    c)On "Connection Properties" screen, specify SQL Server Name. If you are using local installationof SQL Server then use (local) or . in the "server name" dropdownlist.

  • 8/10/2019 Entity Framework Video Content

    5/61

    d)Specify the Authentication you want to use.

    e)Select the database from "Select or enter database name" dropdownlist.

    f)Finally "Test connection" and click "OK"

    g)At this point we should be back on "Choose Your Data Connection" window. Make sure "Save

    entity connection settings in Web.Config as" checkbox is selected and change the name of theconnection string to "EmployeeDBContext" and then Click "Next"

    Step 8:On "Choose Your Database Objects" screen, select "Departments" and "Employees"

    tables. Change the Model Namespace to "EmployeeModel" and click "Finish". At this point you

    should have EmployeeModel.edmx created.

    EmployeeModel.Designer.csfile is also generated. This file contains Employee and Departmentclasses. Tables are mapped to classes and columns are mapped to class properties.

    Step 9: Add a webform. Drag and drop a GridView and an EntityDataSource control on the

    webform.

    Step 10:Build the solution. Flip the WebForm1.aspx to design mode.

    a)Right click on EntityDataSource control and select "Show smart tag" option from the context

    menu.

    b)Click on "Configure Data Source" link

    c)Select "Named Connection" radiobutton and select "EmployeeDBContext" from the

    dropdownlist.

    d)Select "EmployeeDBContext" option from "DefaultContainerName" dropdownlist and click

    "Next"

    e)On "Configure Data Selection" screen, select "Departments" from "EntitySetName"

    dropdownlist and click "Finish"

    f)Right click on "GridView1" control and select "Show smart tag" option.

    g)Click on "Auto Format" link and select "Colorful" option from "AutoFormat" window and click

    "OK".

  • 8/10/2019 Entity Framework Video Content

    6/61

    h)Select "EntityDataSource1" from "Choose Data Source" dropdownlist.

    I)Click on "Eidt Columns" link and add a "Template Field". Set HeaderText=Employees and click

    OK.

    j)Now click "Edit Templates" link.

    k)Drag and drop a GridView controll)Select "Edit DataBindings" link

    m)Select "Custom binding" radiobutton and type Eval("Employees") in "Code expression"

    textbox and click OK.

    n)Select "End Template Editing" option from "GridView1" smart tasks pane.

    Step 11: Right click on "EntityDataSource1" control and select "Properties". In properties window

    set Include=Employees

    Run the web application and notice that Departments and Employees are displayed as expected.We have achieved all this without writing a single line of code.

    In this demo, we have used schema first approach of entity framework. We can also use Model

    First or Code First approaches. We will discuss these in our subsequent videos.

    Part 2 - Entity Framework Model First Approach

    Suggested Videos

    Part 1 - What is Entity Framework

    In this video we will discuss using Model First Approach of Entity Framework. This is continuation

    toPart 1.Please watchPart 1before proceeding.

    Entity Framework supports the following three approaches

    1.Schema First Approach - Discussed inPart 12.Model First Approach - In this video.

    http://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.html
  • 8/10/2019 Entity Framework Video Content

    7/61

    3.Code First Approach - Next Video

    In the Model First Approach, We first create the Entity Model. That is we create

    1.Entities

    2.Relationships Between Entities

    3.Inheritance hierarchies etc.

    We do all this directly on the design surface of the EDMX file. We will be continuing with the

    same example that we started inPart 1ofEntity Framework Tutorial.

    Step 1:First delete the "EmployeeModel.edmx" file from the existing solution

    Step 2:Add a new "ADO.NET Entity Data Model" file with name = EmployeeModel.

    Step 3: On "Choose Model Contents" screen, select "Empty Model" and click "Finish"

    Step 4:At this point, we have a blank EmployeeModel.edmx file added to the solution. Now, right

    click on the designer surface and then select : Add - Entity. Set,

    Entity Name = Department

    Base Type = None

    Entity Set = Departments

    Create Key property = Select the check box

    Property Name = Id

    Property Type = Int32

    Finally click OK.

    http://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttps://www.youtube.com/playlist?list=PL6n9fhu94yhUPBSX-E2aJCnCR3-_6zBZxhttps://www.youtube.com/playlist?list=PL6n9fhu94yhUPBSX-E2aJCnCR3-_6zBZxhttps://www.youtube.com/playlist?list=PL6n9fhu94yhUPBSX-E2aJCnCR3-_6zBZxhttps://www.youtube.com/playlist?list=PL6n9fhu94yhUPBSX-E2aJCnCR3-_6zBZxhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.html
  • 8/10/2019 Entity Framework Video Content

    8/61

    Step 5:Right click on "Department" entity and select "Add - Scalar Property". Change the

    property name to "Name". Right click on the "Name" property that we just added and select

    "properties" from the context menu. Notice that the "Type" of "Name" property is set to

    "String".

    Step 6: Similarly add "Location" property for the "Department" entity. At this point, the

    "Department" entity should look as shown below.

    Step 7:Add "Employee" entity and the following scalar properties.

    FirstName (Type = string)

    LastName (Type = string)

  • 8/10/2019 Entity Framework Video Content

    9/61

    Gender (Type = string)

    Salary (Type = int)

    Step 8: At this point, Department and Employee entities should look as shown below.

    Step 9:We need to add "Employees" navigation property for the "Department" entity, and

    "Department" navigation property for the "Employee" entity. To do this, right click on

    the design surface and select "Add - Association". In the "Add Association" window, set values as

    shown in the image below and click "OK"

  • 8/10/2019 Entity Framework Video Content

    10/61

    Step 10:At this point, we should have the following created.

    a)Employees navigation property in the Department entity

    b)Department navigation property in the Employee entity

    c)DepartmentId scalar property

    Step 11:Right click on the design surface, and select "Genedrate Database from Model..." option

    Step 12: On "Choose Your Data Connection"screen, click "Next"

    Step 13: At this point, we should have the required SQL generated to create

    a)Departments table

    b)Employees table

    c)Primary key constraints for Departments and Employees tablesd)Foreign key constraint

    e)Indexes

    Step 14: Click Finish. Now, we should have "EmployeeModel.edmx.sql" file generated with the

    required SQL. If you already have "Departments" and "Employees" tables in the database, delete

    them. Right click on the file and select "Execute SQL" option from the context menu.

    Step 15: Populate the "Departments" and "Employees" tables with sample data using the script

    below.

    InsertintoDepartments values ('IT', 'New York')InsertintoDepartments values ('HR', 'London')

    InsertintoDepartments values ('Payroll', 'Sydney')

    InsertintoEmployees values ('Mark', 'Hastings', 'Male', 60000, 1)

    InsertintoEmployees values ('Steve', 'Pound', 'Male', 45000, 3)

    InsertintoEmployees values ('Ben', 'Hoskins', 'Male', 70000, 1)

    InsertintoEmployees values ('Philip', 'Hastings', 'Male', 45000, 2)

    InsertintoEmployees values ('Mary', 'Lambeth', 'Female', 30000, 2)

    InsertintoEmployees values ('Valarie', 'Vikings', 'Female', 35000, 3)

    InsertintoEmployees values ('John', 'Stanmore', 'Male', 80000, 1)

  • 8/10/2019 Entity Framework Video Content

    11/61

    Step 16:Run the application by pressing CTRL + F5. We will get the following runtime error.

    The specified default EntityContainer name 'EmployeeDBContext' could not be found in the

    mapping and metadata information.

    Parameter name: defaultContainerName

    Step 17:Open WebForm1.aspx in source mode, and set ConnectionString and

    DefaultContainerName properties of EntityDataSource control as shown below.

    At this point we should get the output we expect.

    Part 3 - Entity Framework Code First Approach

    Suggested Videos

    Part 1 - What is Entity Framework

    Part 2 - Entity Framework Model First Approach

    Entity Framework supports

    1.Database first or schema first approach -Discussed in Part 12.Model first appraoch -Discussed in Part 2

    3.Code first approach - In this video

    Code-first approach allows us to create our custom classes first and based on those custom

    classes entity framework can generate database automatically for us.Let's understand this with

    an example. We will be modifying the example we worked with inPart 2.

    Step 1:Delete EmployeeModel.edmx && EmployeeModel.edmx.sql files from the solution

    explorer.

    Step 2: Add a class file to the project. Name it Employee.cs. Copy and paste the following code.

    publicclassEmployee

    {

    // Scalar Properties

    publicintId{ get; set; }

    publicstringFirstName{ get; set; }

    publicstringLastName{ get; set; }

    publicstringGender{ get; set; }

    publicintSalary{ get; set; }

    // Navigation Property

    http://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-2-entity-framework-model-first_5.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-2-entity-framework-model-first_5.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-2-entity-framework-model-first_5.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-2-entity-framework-model-first_5.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-2-entity-framework-model-first_5.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-2-entity-framework-model-first_5.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-2-entity-framework-model-first_5.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-2-entity-framework-model-first_5.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-2-entity-framework-model-first_5.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-2-entity-framework-model-first_5.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-2-entity-framework-model-first_5.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.html
  • 8/10/2019 Entity Framework Video Content

    12/61

    publicDepartmentDepartment{ get; set; }

    }

    Step 3: Add a class file to the project. Name it Department.cs. Copy and paste the following code.

    publicclassDepartment

    {

    // Scalar Properties

    publicintId{ get; set; }

    publicstringName{ get; set; }

    publicstringLocation{ get; set; }

    // Navigation Property

    publicListEmployees{ get; set; }

    }

    Step 4:Add a class file to the project. Name it EmployeeDBContext.cs. Copy and paste thefollowing code.

    // EmployeeDBContext class must inherit from DbContext

    // present in System.Data.Entity namespace

    publicclassEmployeeDBContext: DbContext

    {

    publicDbSetDepartments{ get; set; }

    publicDbSetEmployees{ get; set; }

    }

    Step 5:Add a class file to the project. Name it EmployeeRepository.cs . Copy and paste thefollowing code.

    publicclassEmployeeRepository

    {

    publicListGetDepartments()

    {

    EmployeeDBContextemployeeDBContext=newEmployeeDBContext();

    returnemployeeDBContext.Departments.Include("Employees").ToList();

    }

    }

    Step 6:Add the database connection string in web.config file.

    Please Note:If ProviderName is not specified the following runtime error will be thrown.

    The connection string 'EmployeeDBContext' in the application's configuration file does not contain

    the required providerName attribute."

  • 8/10/2019 Entity Framework Video Content

    13/61

    Step 7:Configure Object Data Source control

    a)Delete EntityDataSource control, that is already there in WebForm1.aspx.

    b)Drag and Drop ObjectDataSource control.

    c)Right click on ObjectDataSource control and select "Show Smart Tag" option from the context

    menu

    d)Click on "Configure Data Source..." link

    e)On "Choose a Business Object" screen, select "EmployeeRepository" and click "Next"

    f)On "Define Data Methods" screen, select GetDepartments() method and click "Finish"

    Step 8: Configure GridView control

    a)Right click on GridView control and select "Show Smart Tag" option from the context menu

    b)Select "ObjectDataSource1" from "Choose Data Source" dropdownlist

    c)Click "No" to "Refresh Fields and Keys for GridView1" when prompted

    Step 9: Rebuild the solution.

    Step 10: Delete the already existing database from SQL Server Management Studio.

    Step 11: Run the application by pressing CTRL + F5. Notice that we don't have any data displayed

    on WebForm1. This is because we don't have any data in the Departments and Employees tables.

    At this point We have the following created automatically.

    a)Sample database

    b)Departments table

    c)Employees table

    Step 12: Use the SQL script to populate the tables with data.InsertintoDepartments values ('IT', 'New York')

    InsertintoDepartments values ('HR', 'London')

    InsertintoDepartments values ('Payroll', 'Sydney')

    InsertintoEmployees values ('Mark', 'Hastings', 'Male', 60000, 1)

    InsertintoEmployees values ('Steve', 'Pound', 'Male', 45000, 3)

    InsertintoEmployees values ('Ben', 'Hoskins', 'Male', 70000, 1)

    InsertintoEmployees values ('Philip', 'Hastings', 'Male', 45000, 2)

    InsertintoEmployees values ('Mary', 'Lambeth', 'Female', 30000, 2)

    InsertintoEmployees values ('Valarie', 'Vikings', 'Female', 35000, 3)InsertintoEmployees values ('John', 'Stanmore', 'Male', 80000, 1)

    Step 13 :Refresh the Web Form and we should see the data we expect.

  • 8/10/2019 Entity Framework Video Content

    14/61

    Part 4 - Customizing table, column and foreign key column names when using entity

    framework code first approach

    Suggested Videos

    Part 1 - What is Entity Framework

    Part 2 - Entity Framework Model First Approach

    Part 3 - Entity Framework Code First Approach

    In this vide we will discuss, customizing table, column and foreign key column names when using

    entity framework code first approach. This is continuation toPart 3.Please watchPart 3before

    proceeding.

    InPart 3,we have discussed generating Departments and Employees tables using Entity

    Framework Code first approach.

    Entity Framework generated the following Employees table. Notice the column names.

    Department_Idcolumn has an underscore in it's name. Let's say we want the column to be

    generated as DepartmenId(without an underscore)

    Entity Framework generated the above Employees table based on the following custom Employee

    class that we created.

    publicclassEmployee

    {

    publicintId{ get; set; }

    publicstringFirstName{ get; set; }

    publicstringLastName{ get; set; }

    publicstringGender{ get; set; }

    publicintSalary{ get; set; }

    publicDepartmentDepartment{ get; set; }

    }

    To achieve this use the ForeignKey attribute present in

    System.ComponentModel.DataAnnotations.Schemanamespace. Modify the Employee class as

    shown below.

    publicclassEmployee

    {

    publicintId{ get; set; }

    publicstringFirstName{ get; set; }

    publicstringLastName{ get; set; }

    http://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-2-entity-framework-model-first_5.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-2-entity-framework-model-first_5.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-2-entity-framework-model-first_5.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-1-what-is-entity-framework.html
  • 8/10/2019 Entity Framework Video Content

    15/61

    publicstringGender{ get; set; }

    publicintSalary{ get; set; }

    publicintDepartmentId{ get; set; }

    [ForeignKey("DepartmentId")]

    publicDepartmentDepartment{ get; set; }

    }

    Rebuild the solution, and run the application.

    You will get the following error. We will discuss the reasons for this error and how to fix it the

    right way in a later video session.

    The model backing the 'EmployeeDBContext' context has changed since the database was

    created. Consider using Code First Migrations to update the database

    (http://go.microsoft.com/fwlink/?LinkId=238269).

    For now to get around the error, delete the Sample database using SQL Server ManagementStudio, and then try to run the application again. A blank webform will be displayed. Now check

    the Employees tables using SQL Server Management Studio and notice that the DepartmentId

    column is created without an underscore as expected.

    To customize the table name, use Table attribute and to customize column name use Column

    attribute.

    For example, to change

    Table name from Employees to tblEmployees and

    FirstName column to First_Name

    We would modify the Employee class as shown below.

    [Table("tblEmployees")]

    publicclassEmployee

    {

    publicintId{ get; set; }

    [Column("First_Name")]

    publicstringFirstName{ get; set; }

    publicstringLastName{ get; set; }

    publicstringGender{ get; set; }

    publicintSalary{ get; set; }

    publicintDepartmentId{ get; set; }

    [ForeignKey("DepartmentId")]publicDepartmentDepartment{ get; set; }

  • 8/10/2019 Entity Framework Video Content

    16/61

    }

    Entity Framework would then generate the following. Notice the table name and First_Name

    column.

    Part 5 - How to handle model changes in entity framework

    Suggested Videos

    Part 2 - Entity Framework Model First Approach

    Part 3 - Entity Framework Code First Approach

    Part 4 - Customizing table & column names

    In this video we will discuss, how to handle model changes after the database is already created.

    This is continuation toPart 4.Please watchPart 4before proceeding.

    At the moment the Employee class is as shown below

    [Table("tblEmployees")]

    publicclassEmployee

    {

    publicintId{ get; set; }

    [Column("First_Name")]

    publicstringFirstName{ get; set; }

    publicstringLastName{ get; set; }

    publicstringGender{ get; set; }

    publicintSalary{ get; set; }

    publicintDepartmentId{ get; set; }

    [ForeignKey("DepartmentId")]

    publicDepartmentDepartment{ get; set; }

    }

    The following is the table Entity Framework has generated based on the above Employee class

    http://csharp-video-tutorials.blogspot.com/2014/05/part-2-entity-framework-model-first_5.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-2-entity-framework-model-first_5.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-4-customizing-table-column-and.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-4-customizing-table-column-and.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-4-customizing-table-column-and.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-4-customizing-table-column-and.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-4-customizing-table-column-and.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-4-customizing-table-column-and.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-4-customizing-table-column-and.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-4-customizing-table-column-and.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-4-customizing-table-column-and.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-4-customizing-table-column-and.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-4-customizing-table-column-and.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-2-entity-framework-model-first_5.html
  • 8/10/2019 Entity Framework Video Content

    17/61

    Now let us add JobTitle property to the Employee class. The modified Employee class is shown

    below.

    [Table("tblEmployees")]

    publicclassEmployee

    {

    publicintId{ get; set; }

    [Column("First_Name")]publicstringFirstName{ get; set; }

    publicstringLastName{ get; set; }

    publicstringGender{ get; set; }

    publicintSalary{ get; set; }

    publicintDepartmentId{ get; set; }

    [ForeignKey("DepartmentId")]

    publicDepartmentDepartment{ get; set; }

    publicstringJobTitle{ get; set; }

    }

    At this point if we run the application, we get the following error.

    The model backing the 'EmployeeDBContext' context has changed since the database was

    created. Consider using Code First Migrations to update the database

    (http://go.microsoft.com/fwlink/?LinkId=238269).

    This is because the model (i.e Employee class) has changed since the database was created. This

    means the Model and the database are no longer in sync and hence we get the error. To check if

    the model has changed since the database was created, entity framework uses

    __MigrationHistory table that is auto-generated.

    To fix this error, we have to tell entity framework what to do when the model changes.

    Add Global.asax file to the web application project. Include the following code in

    Application_Start() method. Here, we are telling the entity framework to drop and recreate

    database every time the model changes.

    Database.SetInitializer(newDropCreateDatabaseIfModelChanges());

    Another option is, to drop and recreate the database always. To drop and recreate the database

    always we would change the code in Application_Start() method as shown below.

    Database.SetInitializer(newDropCreateDatabaseAlways());

    Please Note:Database class is present in System.Data.Entity namespace.

  • 8/10/2019 Entity Framework Video Content

    18/61

    Run the application, and notice that the database is dropped and recreated. But the webform

    does not display any data, as there is no data in Departments and tblEmployees tables. For now

    let's manually populate the tables using the followng SQL script.

    InsertintoDepartments values ('IT', 'New York')

    InsertintoDepartments values ('HR', 'London')

    InsertintoDepartments values ('Payroll', 'Sydney')

    InsertintotblEmployees values ('Mark', 'Hastings', 'Male', 60000, 1, 'Developer')

    InsertintotblEmployees values ('Steve', 'Pound', 'Male', 45000, 3, 'Manager')

    InsertintotblEmployees values ('Ben', 'Hoskins', 'Male', 70000, 1, 'Developer')

    InsertintotblEmployees values ('Philip', 'Hastings', 'Male', 45000, 2, 'Recruiter')

    InsertintotblEmployees values ('Mary', 'Lambeth', 'Female', 30000, 2, 'Recruiter')

    InsertintotblEmployees values ('Valarie', 'Vikings', 'Female', 35000, 3, 'Manager')

    InsertintotblEmployees values ('John', 'Stanmore', 'Male', 80000, 1, 'Developer')

    Referesh the webform. Notice that JobTitle is not displayed on the WebForm. To fix this add a

    boundfield to the GridView control that displays Employees details as shown below.

    Part 6 - How to seed database with test data using entity framework

    Suggested Videos

    Part 3 - Entity Framework Code First Approach

    Part 4 - Customizing table & column names

    Part 5 - How to handle model changes in entity framework

    So far in this video series, we have been manually populating the database with test data using

    the insert sql script. Entity Framework can automate this. We will be working with the example we

    worked with inPart 5.Here are the steps.

    Step 1:Right click on the project in solution explorer and add a class file with name =

    EmployeeDBContextSeeder.cs

    Step 2: Copy and paste the following code in EmployeeDBContextSeeder.cs file

    usingSystem.Collections.Generic;usingSystem.Data.Entity;

    http://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-4-customizing-table-column-and.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-4-customizing-table-column-and.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-5-how-to-handle-model-changes-in.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-5-how-to-handle-model-changes-in.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-5-how-to-handle-model-changes-in.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-5-how-to-handle-model-changes-in.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-5-how-to-handle-model-changes-in.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-5-how-to-handle-model-changes-in.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-5-how-to-handle-model-changes-in.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-4-customizing-table-column-and.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-3-entity-framework-code-first_6.html
  • 8/10/2019 Entity Framework Video Content

    19/61

    namespaceEntityFrameworkDemo

    {

    publicclassEmployeeDBContextSeeder:

    DropCreateDatabaseIfModelChanges

    {

    protectedoverridevoidSeed(EmployeeDBContextcontext)

    {

    Departmentdepartment1=newDepartment()

    {

    Name="IT",

    Location="New York",

    Employees=newList()

    {

    newEmployee()

    {

    FirstName="Mark",LastName="Hastings",

    Gender="Male",

    Salary=60000,

    JobTitle="Developer"

    },

    newEmployee()

    {

    FirstName="Ben",

    LastName="Hoskins",

    Gender="Male",Salary=70000,

    JobTitle="Sr. Developer"

    },

    newEmployee()

    {

    FirstName="John",

    LastName="Stanmore",

    Gender="Male",

    Salary=80000,

    JobTitle="Project Manager"}

    }

    };

    Departmentdepartment2=newDepartment()

    {

    Name="HR",

    Location="London",

    Employees=newList()

    {newEmployee()

  • 8/10/2019 Entity Framework Video Content

    20/61

    {

    FirstName="Philip",

    LastName="Hastings",

    Gender="Male",

    Salary=45000,

    JobTitle="Recruiter"

    },

    newEmployee()

    {

    FirstName="Mary",

    LastName="Lambeth",

    Gender="Female",

    Salary=30000,

    JobTitle="Sr. Recruiter"

    }

    }};

    Departmentdepartment3=newDepartment()

    {

    Name="Payroll",

    Location="Sydney",

    Employees=newList()

    {

    newEmployee()

    {

    FirstName="Steve",LastName="Pound",

    Gender="Male",

    Salary=45000,

    JobTitle="Sr. Payroll Admin",

    },

    newEmployee()

    {

    FirstName="Valarie",

    LastName="Vikings",

    Gender="Female",Salary=35000,

    JobTitle="Payroll Admin",

    }

    }

    };

    context.Departments.Add(department1);

    context.Departments.Add(department2);

    context.Departments.Add(department3);

    base.Seed(context);

  • 8/10/2019 Entity Framework Video Content

    21/61

    }

    }

    }

    Step 3:Copy and paste the following line in Application_Start() method Global.asax file

    Database.SetInitializer(newEmployeeDBContextSeeder());

    Step 4:Remove the following Table and Column attributes from Employee.cs file.

    [Table("tblEmployees")]

    [Column("First_Name")]

    At this point Employee class should look as shown below

    publicclassEmployee

    {

    publicintId{ get; set; }

    publicstringFirstName{ get; set; }publicstringLastName{ get; set; }

    publicstringGender{ get; set; }

    publicintSalary{ get; set; }

    publicintDepartmentId{ get; set; }

    [ForeignKey("DepartmentId")]

    publicDepartmentDepartment{ get; set; }

    publicstringJobTitle{ get; set; }

    }

    Step 5:Run the application and notice that the Sample database, Departments and Employeestables are created and populated with test data automatically.

    Part 7 - Using stored procedures with entity framework

    Suggested Videos

    Part 4 - Customizing table & column names

    Part 5 - How to handle model changes in entity framework

    Part 6 - How to seed database with test data using entity framework

    In this video we will discuss using our own custom stored procedures to perform Insert, Update

    and Delete operations using entity framework. We will be using the following Employees table

    for this demo.

    http://csharp-video-tutorials.blogspot.com/2014/05/part-4-customizing-table-column-and.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-4-customizing-table-column-and.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-5-how-to-handle-model-changes-in.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-5-how-to-handle-model-changes-in.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-6-how-to-seed-database-with-test.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-6-how-to-seed-database-with-test.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-6-how-to-seed-database-with-test.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-5-how-to-handle-model-changes-in.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-4-customizing-table-column-and.html
  • 8/10/2019 Entity Framework Video Content

    22/61

    Step 1:Use the following SQL Script to create and populate Employee table.

    CreatetableEmployees

    (

    ID intprimarykeyidentity,

    Name nvarchar(50),

    Gender nvarchar(50),Salary int

    )

    InsertintoEmployees values ('Mark', 'Male', 60000)

    InsertintoEmployees values ('Steve', 'Male', 45000)

    InsertintoEmployees values ('Ben', 'Male', 70000)

    InsertintoEmployees values ('Philip', 'Male', 45000)

    InsertintoEmployees values ('Mary', 'Female', 30000)

    InsertintoEmployees values ('Valarie', 'Female', 35000)

    InsertintoEmployees values ('John', 'Male', 80000)

    Step 2:Create Insert, Update and Delete stored procedures

    CreateprocedureInsertEmployee

    @Name nvarchar(50),

    @Gender nvarchar(50),

    @Salary int

    as

    Begin

    InsertintoEmployees values (@Name, @Gender, @Salary)

    End

    Go

    CreateprocedureUpdateEmployee

    @ID int,

    @Name nvarchar(50),

    @Gender nvarchar(50),

    @Salary int

    as

    Begin

    UpdateEmployees SetName = @Name, Gender = @Gender,

    Salary = @Salary

  • 8/10/2019 Entity Framework Video Content

    23/61

    whereID = @ID

    End

    Go

    CreateprocedureDeleteEmployee

    @ID int

    as

    Begin

    DeletefromEmployees whereID = @ID

    End

    Go

    Step 3:Create a new empty asp.net web application

    Step 4: Add a new ADO.NET Entity Data Model.

    a)On Choose Model Contentsscreen select "Generate from database"option and click Next

    b)On "Choose Your Data Connections" screen give a meaningful name for the connection string

    that will be stored in the web.config file. I have named it EmployeeDBContext. Click Next.

    c)On "Choose Your Database Objects" screen, select Employees Table and the 3 storedprocedures (InsertEmployee, UpdateEmployee, DeleteEmployee). Provide a meaningful name for

    the Model namespace. I have named it EmployeeModel. CLick Finish.

  • 8/10/2019 Entity Framework Video Content

    24/61

    At this point on the ADO.NET Entity Model designer surface, we should be able to see the

    Employee entity but not the stored procedures.

    To view the stored procedures,

    1.Right click on entity model designer surface and select "Model Broswer" from the context

    menu.

    2.Expand Stored Procedures folder

    Step 5:Add a web form to the project. Drag and drop the following 3 controls and build thesolution.

  • 8/10/2019 Entity Framework Video Content

    25/61

    1.GridView

    2.DetailsView

    3.EntityDataSource

    Step 6: Configure EntityDataSource control

    a). Right click on EntityDataSource control and select "Show Smart Tag" option

    b)Click on Configure Data Source link

    c)Select EmployeeDBContext from the Named Connection dropdownlist and click Next

    d)Select the options on "Configure Data Selection" screen as shown in the image below and click

    Finish

    Step 7:Configure GridView control

    a). Right click on GridView control and select "Show Smart Tag" option

    b)Click on "Auto Format" link and select "Colourful" scheme

    c)Select "EntityDataSource1" from "Choose Data Source" dropdownlist

  • 8/10/2019 Entity Framework Video Content

    26/61

    d)Select Enable Editing and Enable Deleting checkboxes

    Step 8:Configure DetailsView control

    a)Right click on DetailsView control and select "Show Smart Tag" option

    b)Click on "Auto Format" link and select "Colourful" scheme

    c)Select "EntityDataSource1" from "Choose Data Source" dropdownlist

    d)Select Enable Inserting checkbox

    e)Set DeafultMode=Insert. Use properties window to set this.

    f)Set InsertVisible="false" for the ID BoundField. You can do this directly in the HTML Source.g)Generate ItemInserted event handler method for DetailsView control. Copy and paste the

    following code.

    protectedvoidDetailsView1_ItemInserted (objectsender, DetailsViewInsertedEventArgse)

    {

    GridView1.DataBind();

    }

    At this point if you run the application, and if you insert, update and delete employees, by default

    entity framework will use the sql it auto-generates and not our custom stored procedures.

    To tell the entity framework to use the stored procedures, we have to map them to the Employee

    entity.

    Here are the steps.

    1.Right click on "Employee" entity on "EmployeeModel.edmx" and select "Stored Procedure

    Mapping" option from the context menu.

    2.In the "Mapping Details" windows specify the Insert, Update and Delete stored procedures

    that you want to use with "Employee" entity

  • 8/10/2019 Entity Framework Video Content

    27/61

    At this point,

    1.Run SQL Profiler

    2.Run the application

    3.Insert, Update and Delete Employee, and notice that the respective stored procedures are

    being called now.

    Part 8 - Using stored procedures with entity framework code first approach

    Suggested Videos

    Part 5 - How to handle model changes in entity framework

    Part 6 - How to seed database with test data using entity framework

    Part 7 - Using stored procedures with entity framework

    In this video we will discuss using stored procedures to perform Insert, Update and Deleteoperations using entity framework code first approach.

    Step 1:Create a new empty asp.net web application project. Name it Demo. Install entity

    framework if it's not already installed.

    Step 2:Add a class file to the project. Name it Employee.cs. Copy and paste the following code.

    namespaceDemo

    {

    publicclassEmployee

    { publicintID { get; set; }

    http://csharp-video-tutorials.blogspot.com/2014/05/part-5-how-to-handle-model-changes-in.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-5-how-to-handle-model-changes-in.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-6-how-to-seed-database-with-test.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-6-how-to-seed-database-with-test.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-7-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-7-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-7-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-6-how-to-seed-database-with-test.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-5-how-to-handle-model-changes-in.html
  • 8/10/2019 Entity Framework Video Content

    28/61

    publicstringName { get; set; }

    publicstringGender { get; set; }

    publicintSalary { get; set; }

    }

    }

    Step 3:Add a class file to the project. Name it EmployeeDBContext.cs. Copy and paste the

    following code.

    usingSystem.Data.Entity;

    namespaceDemo

    {

    publicclassEmployeeDBContext: DbContext

    {

    publicDbSet Employees { get; set; }

    protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder){

    // This line will tell entity framework to use stored procedures

    // when inserting, updating and deleting Employees

    modelBuilder.Entity().MapToStoredProcedures();

    base.OnModelCreating(modelBuilder);

    }

    }

    }

    Step 4:Add a class file to the project. Name it EmployeeRepository.cs . Copy and paste thefollowing code.

    usingSystem.Collections.Generic;

    usingSystem.Linq;

    namespaceDemo

    {

    publicclassEmployeeRepository

    {

    EmployeeDBContextemployeeDBContext = newEmployeeDBContext();

    publicList GetEmployees(){

    returnemployeeDBContext.Employees.ToList();

    }

    publicvoidInsertEmployee(Employeeemployee)

    {

    employeeDBContext.Employees.Add(employee);

    employeeDBContext.SaveChanges();

    }

    publicvoidUpdateEmployee(Employeeemployee)

  • 8/10/2019 Entity Framework Video Content

    29/61

    {

    EmployeeemployeeToUpdate = employeeDBContext

    .Employees.SingleOrDefault(x => x.ID == employee.ID);

    employeeToUpdate.Name = employee.Name;

    employeeToUpdate.Gender = employee.Gender;

    employeeToUpdate.Salary = employee.Salary;

    employeeDBContext.SaveChanges();

    }

    publicvoidDeleteEmployee(Employeeemployee)

    {

    EmployeeemployeeToDelete = employeeDBContext

    .Employees.SingleOrDefault(x => x.ID == employee.ID);

    employeeDBContext.Employees.Remove(employeeToDelete);

    employeeDBContext.SaveChanges();

    }}

    }

    Step 5:Add the database connection string in web.config file.

    Step 6:Add a webform to the project. Drag and drop the following 3 controls and build the

    solution.

    1.GridView

    2.DetailsView

    3.ObjectDataSource

    Step 7:Configure ObjectDataSource control

    a). Right click on ObjectDataSource control and select "Show Smart Tag" option

    b)Click on Configure Data Source link

    c)Select Demo.EmployeeRepository on Choose a Business Object screen and click Nextd)On Define Data Methods screen

    i)On SELECT tab - Select GetEmployees() method

    ii)On UPDATE tab - Select UpdateEmployees(Employee employee) method

    iii)On INSERT tab - Select InsertEmployees(Employee employee) method

    iv)On DELETE tab - Select DeletEmployees(Employee employee) method

    Step 8: Configure GridView control

    a). Right click on GridView control and select "Show Smart Tag" option

    b)Click on "Auto Format" link and select "Colourful" scheme

    c)Select "ObjectDataSource1" from "Choose Data Source" dropdownlistd)Select Enable Editing and Enable Deleting checkboxes

  • 8/10/2019 Entity Framework Video Content

    30/61

    e)Set DataKeyNames="ID". Do this in the properties window of the GridView control

    Step 9: Configure DetailsView control

    a)Right click on DetailsView control and select "Show Smart Tag" option

    b)Click on "Auto Format"link and select "Colourful" scheme

    c)Select "ObjectDataSource1" from "Choose Data Source" dropdownlist

    d)Select Enable Inserting checkbox

    e)Set DeafultMode=Insert. Use properties window to set this.

    f)Set InsertVisible="false" for the ID BoundField. You can do this directly in the HTML Source.

    Step 10:If you already have Sample database in SQL Server. Delete it from SQL Server

    Management Studio.

    Step 11: Run the application by pressing CTRL + F5. Notice that we don't have any data displayed

    on WebForm1. This is because we don't have any data in the Employees table.

    At this point we have the Sample database and Employees table created automatically. The

    following stored procedures are also automatically created.

    Employee_Delete

    Employee_Insert

    Employee_Update

    By default, the following should be the naming convention for the stored procedures.

    INSERT stored procedure - [Entity_Name]_Insert. Insert Stored procedure should return the auto-

    generated identity column value.

    UPDATE stored procedure- [Entity_Name]_UpdateDELETE stored procedure- [Entity_Name]_Delete

    Step 12:Use the below SQL script to populate Employees tables with test data.

    InsertintoEmployees values ('Mark', 'Male', 60000)

    InsertintoEmployees values ('Steve', 'Male', 45000)

    InsertintoEmployees values ('Ben', 'Male', 70000)

    InsertintoEmployees values ('Philip', 'Male', 45000)

    InsertintoEmployees values ('Mary', 'Female', 30000)

    InsertintoEmployees values ('Valarie', 'Female', 35000)

    InsertintoEmployees values ('John', 'Male', 80000)

    At this point,

    1.Run SQL Prrofiler

    2.Run the application

    3.Insert, Update and Delete Employees, and notice that the respective stored procedures are

    being called as expected.

  • 8/10/2019 Entity Framework Video Content

    31/61

    Part 9 - Overriding stored procedure defaults with entity framework code first

    approach

    Suggested Videos

    Part 6 - How to seed database with test data using entity framework

    Part 7 - Using stored procedures with entity framework

    Part 8 - Using stored procedures with entity frameowrk code first approach

    In this video we will discuss, changing the default Insert, Update and Delete stored procedure

    names that are auto-generated by entity framework code first approach. This is continuation to

    Part 8.Please watchPart 8before proceeding.

    publicclassEmployeeDBContext: DbContext

    {

    publicDbSet Employees { get; set; }

    protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder)

    {

    modelBuilder.Entity().MapToStoredProcedures();

    base.OnModelCreating(modelBuilder);

    }

    }

    By default, the code above generates the following 3 stored procedures for Inserting, Updating

    and Deleting Employee objects.Employee_Insert

    Employee_Update

    Employee_Delete

    If you want to override or change the default names of auto-generated stored procedures, change

    the code in EmployeeDBContext class as shown below.

    publicclassEmployeeDBContext: DbContext

    {

    publicDbSet Employees { get; set; }

    protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder)

    {

    modelBuilder.Entity()

    .MapToStoredProcedures(p => p.Insert(x => x.HasName("InsertEmployee")));

    modelBuilder.Entity()

    .MapToStoredProcedures(p => p.Update(x => x.HasName("UpdateEmployee")));

    modelBuilder.Entity()

    .MapToStoredProcedures(p => p.Delete(x => x.HasName("DeleteEmployee")));

    base.OnModelCreating(modelBuilder);}

    http://csharp-video-tutorials.blogspot.com/2014/05/part-6-how-to-seed-database-with-test.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-6-how-to-seed-database-with-test.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-7-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-7-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-8-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-8-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-8-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-8-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-8-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-8-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-8-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-8-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-8-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-8-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-7-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-6-how-to-seed-database-with-test.html
  • 8/10/2019 Entity Framework Video Content

    32/61

    }

    At this point delete the Sample database and run WebForm1 again. Notice that the generated

    stored procedures now have the names we specified.

    The above code can also be rewritten as shown below

    publicclassEmployeeDBContext: DbContext

    {

    publicDbSet Employees { get; set; }

    protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder)

    {

    modelBuilder.Entity().MapToStoredProcedures

    (p => p.Insert(i => i.HasName("InsertEmployee"))

    .Update(u => u.HasName("UpdateEmployee"))

    .Delete(d => d.HasName("DeleteEmployee"))

    );

    base.OnModelCreating(modelBuilder);

    }

    }

    The default parameter names of the stored procedures can also be changed using the following

    code.

    publicclassEmployeeDBContext: DbContext

    {

    publicDbSet Employees { get; set; }

    protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder)

    {

    modelBuilder.Entity().MapToStoredProcedures

    (p => p.Insert(i => i.HasName("InsertEmployee")

    .Parameter(n => n.Name, "EmployeeName")

    .Parameter(n => n.Gender, "EmployeeGender")

    .Parameter(n => n.Salary, "EmployeeSalary"))

    .Update(u => u.HasName("UpdateEmployee")

    .Parameter(n => n.ID, "EmployeeID")

    .Parameter(n => n.Name, "EmployeeName")

    .Parameter(n => n.Gender, "EmployeeGender")

    .Parameter(n => n.Salary, "EmployeeSalary"))

    .Delete(d => d.HasName("DeleteEmployee")

    .Parameter(n => n.ID, "EmployeeID")));

  • 8/10/2019 Entity Framework Video Content

    33/61

    base.OnModelCreating(modelBuilder);

    }

    }

    At this point drop the Sample database and run WebForm1 again. Notice that the stored

    procedure parameters have the names we specified.

    Part 10 - Entity splitting in entity framework

    Suggested Videos

    Part 7 - Using stored procedures with entity framework

    Part 8 - Using stored procedures with entity frameowrk code first approach

    Part 9 - Overriding stored procedure defaults with entity frameowrk code first approach

    Entity splitting refers to mapping an entity to two or more tables when the tables share a

    common key. Let us understand Entity splitting with an example.

    We have the following 2 tables. Notice that both the table share the common key - EmployeeID.

    Employees Table

    http://csharp-video-tutorials.blogspot.com/2014/05/part-7-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-7-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-8-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-8-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-9-overriding-stored-procedure.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-9-overriding-stored-procedure.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-9-overriding-stored-procedure.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-8-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-7-using-stored-procedures-with.html
  • 8/10/2019 Entity Framework Video Content

    34/61

    EmployeeContactDetails Table

    SQL Script to create the database objects and populate them with test data

    CreatetableEmployees

    (

    EmployeeID intprimarykeyidentity,

    FirstName nvarchar(50),

    LastName nvarchar(50),

    Gender nvarchar(50))

    GO

    CreatetableEmployeeContactDetails

    (

    EmployeeID intprimarykey,

    Email nvarchar(50),

    Mobile nvarchar(50),

    LandLine nvarchar(50)

    )

    GO

    InsertintoEmployees values ('Mark', 'Hastings', 'Male')

    InsertintoEmployees values ('Steve', 'Pound', 'Male')

    InsertintoEmployees values ('Ben', 'Hoskins', 'Male')

    InsertintoEmployees values ('Philip', 'Hastings', 'Male')

    InsertintoEmployees values ('Mary', 'Lambeth', 'Female')

    InsertintoEmployeeContactDetails values

    (1, '[email protected]', '111111111', '111111111')

    InsertintoEmployeeContactDetails values

    (2, '[email protected]', '2222222222', '2222222222')

    InsertintoEmployeeContactDetails values

    (3, '[email protected]', '3333333333', '3333333333')

    InsertintoEmployeeContactDetails values

    (4, '[email protected]', '44444444444', '44444444444')

    InsertintoEmployeeContactDetails values

    (5, '[email protected]', '5555555555', '5555555555')

    Now, when we use ADO.NET Entity Framework to generate entities from the database using

    database first approach, by default 2 entities will be created, i.e Empoyee andEmployeeContactDetail entities.

  • 8/10/2019 Entity Framework Video Content

    35/61

    There is a one to one mapping between tables and entities. We want a single Employee to map to

    both Employees &EmployeeContactDetailstable.

    To achieve this

    1.Cut Email, Mobile and LandLine properties from EmployeeContactDetail entity and paste them

    in Employeeentity

    2.Delete EmployeeContactDetail entity. On "Delete Unmapped Tables and Views" window click

    NO.

    3.Right click on Employee entity and select "Table Mapping" option from the context menu. Map

    EmployeeId, Email, Mobile and LandLine properties to the respective columns of

    EmployeeContactDetails table.

    At this point we have only one Entity. Build the solution. Add a WebForm. Drag and drop the

    following 3 controls.

    1.GridView

    2.DetailsView

    3.EntityDataSource

    Configure EntityDataSource controla). Right click on EntityDataSource control and select "Show Smart Tag" option

  • 8/10/2019 Entity Framework Video Content

    36/61

    b)Click on Configure Data Source link

    c)Select EmployeeDBContext from the Named Connection dropdownlist and click Next

    d)Select Employees from EntitySetName dropdownlist and enable Inserts, Updates and Deletes.

    Configure GridView control

    a). Right click on GridView control and select "Show Smart Tag" option

    b)Click on "Auto Format" link and select "Colourful" scheme

    c)Select "EntityDataSource1" from "Choose Data Source" dropdownlist

    d)Select Enable Editing and Enable Deleting checkboxes

    Configure DetailsView control

    a)Right click on DetailsView control and select "Show Smart Tag" option

    b)Click on "Auto Format" link and select "Colourful" scheme

    c)Select "EntityDataSource1" from "Choose Data Source" dropdownlist

    d)Select Enable Inserting checkbox

    e)Set DeafultMode=Insert. Use properties window to set this.f)Set InsertVisible="false" for the EmployeeID BoundField. You can do this directly in the HTML

    Source.

    g)Generate ItemInserted event handler method for DetailsView control. Copy and paste the

    following code.

    protectedvoidDetailsView1_ItemInserted(objectsender, DetailsViewInsertedEventArgse)

    {

    GridView1.DataBind();

    }

    At this point run the application. Insert, update and delete an Employee, and notice that both the

    tables (Employees and EmployeeContactDetails) are updated as expected.

    Part 11 - Entity splitting in entity framework with code first approach

    Suggested Videos

    Part 8 - Using stored procedures with entity frameowrk code first approach

    Part 9 - Overriding stored procedure defaults with entity frameowrk code first approach

    Part 10 - Entity splitting in entity framework

    Entity splitting refers to mapping an entity to two or more tableswhen the tables share a

    common key. We discussed, Entity splitting with database first approach inPart 10.In this video

    we will discuss Entity splitting with code first approach.

    Step 1:Create a new empty asp.net web application project. Name it Demo. Install entityframework if it's not already installed.

    http://csharp-video-tutorials.blogspot.com/2014/05/part-8-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-8-using-stored-procedures-with.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-9-overriding-stored-procedure.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-9-overriding-stored-procedure.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-10-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-10-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-10-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-10-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-10-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-10-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-10-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-9-overriding-stored-procedure.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-8-using-stored-procedures-with.html
  • 8/10/2019 Entity Framework Video Content

    37/61

    Step 2: Add a class file to the project. Name it Employee.cs. Copy and paste the following code.

    namespaceDemo

    {

    publicclassEmployee

    {

    // These property values should be stored in Employees Table

    publicintEmployeeId{ get; set; }

    publicstringFirstName{ get; set; }

    publicstringLastName{ get; set; }

    publicstringGender{ get; set; }

    // These property values should be stored in EmployeeContactDetails Table

    publicstringEmail{ get; set; }

    publicstringMobile{ get; set; }

    publicstringLandline{ get; set; }}

    }

    Step 3: Add a class file to the project. Name it EmployeeDBContext.cs. Copy and paste the

    following code.

    usingSystem.Data.Entity;

    namespaceDemo

    {

    publicclassEmployeeDBContext: DbContext

    {publicDbSetEmployees{ get; set; }

    }

    }

    Step 4:Add a class file to the project. Name it EmployeeRepository.cs. Copy and paste the

    following code.

    usingSystem.Collections.Generic;

    usingSystem.Linq;

    namespaceDemo

    {publicclassEmployeeRepository

    {

    EmployeeDBContextemployeeDBContext=newEmployeeDBContext();

    publicListGetEmployees()

    {

    returnemployeeDBContext.Employees.ToList();

    }

    publicvoidInsertEmployee(Employeeemployee){

  • 8/10/2019 Entity Framework Video Content

    38/61

  • 8/10/2019 Entity Framework Video Content

    39/61

    ii) On UPDATE tab - Select UpdateEmployee(Employee employee) method

    iii) On INSERT tab - Select InsertEmployee(Employee employee) method

    iv) On DELETE tab - Select DeletEmployee(Employee employee) method

    Step 8: Configure GridView control

    a). Right click on GridView control and select "Show Smart Tag" option

    b)Click on "Auto Format" link and select "Colourful" scheme

    c)Select "ObjectDataSource1" from "Choose Data Source" dropdownlist

    d)Select Enable Editing and Enable Deleting checkboxes

    e)Set DataKeyNames="EmployeeId". Do this in the properties window of the GridView control

    f)Set ReadOnly="true" for the EmployeeId BoundField. You can do this directly in the HTML

    Source.

    Step 9: Configure DetailsView control

    a)Right click on DetailsView control and select "Show Smart Tag" option

    b)Click on "Auto Format" link and select "Colourful" schemec)Select "ObjectDataSource1" from "Choose Data Source" dropdownlist

    d)Select Enable Inserting checkbox

    e)Set DeafultMode=Insert. Use properties window to set this.

    f)Set InsertVisible="false" for the EmployeeId BoundField. You can do this directly in the HTML

    Source.

    g)Generate ItemInserted event handler method for DetailsView control. Copy and paste the

    following code.

    protectedvoidDetailsView1_ItemInserted(objectsender, DetailsViewInsertedEventArgse)

    {

    GridView1.DataBind();}

    Step 10: If you already have Sample database in SQL Server. Delete it from SQL Server

    Management Studio.

    Step 11: Run the application by pressing CTRL + F5. By default entity framework creates one Table

    i.e Employees table.But we want entity framework to create the following 2 tables.

    a)Employees table with columns EmployeeId, FirstName, LastName and Gender

    b)EmployeeContactDetails table with columns EmployeeId, Email, Mobile and Landline

    Step 12: Override OnModelCreating() method to tell entity framework to generate 2

    tables(Employees& EmployeeContactDetails) for the Employee entity. OnModelCreating()

    method is a virtual method present in DbContext class. So, modify EmployeeDBContext class in

    EmployeeDBContext.csfile as shown below.

    publicclassEmployeeDBContext: DbContext

    {

    publicDbSetEmployees{ get; set; }

    protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder)

    {modelBuilder.Entity()

  • 8/10/2019 Entity Framework Video Content

    40/61

    // Specify properties to map to Employees table

    .Map(map=>

    {

    map.Properties(p=>new

    {

    p.EmployeeId,

    p.FirstName,

    p.LastName,

    p.Gender

    });

    map.ToTable("Employees");

    })

    // Specify properties to map to EmployeeContactDetails table

    .Map(map=>

    {map.Properties(p=>new

    {

    p.EmployeeId,

    p.Email,

    p.Mobile,

    p.Landline

    });

    map.ToTable("EmployeeContactDetails");

    });

    base.OnModelCreating(modelBuilder);

    }

    }

    Step 13:Delete the Sample database and run the web application.

    Step 14: Notice that now we have 2 tablesgenerated by entity framework as expected.

  • 8/10/2019 Entity Framework Video Content

    41/61

    Step 15:Execute the following SQL script to populate the tables with test data.

    InsertintoEmployees values ('Mark', 'Hastings', 'Male')

    InsertintoEmployees values ('Steve', 'Pound', 'Male')

    InsertintoEmployees values ('Ben', 'Hoskins', 'Male')

    InsertintoEmployees values ('Philip', 'Hastings', 'Male')

    InsertintoEmployees values ('Mary', 'Lambeth', 'Female')

    InsertintoEmployeeContactDetails values

    (1, '[email protected]', '111111111', '111111111')

    InsertintoEmployeeContactDetails values

    (2, '[email protected]', '2222222222', '2222222222')

    InsertintoEmployeeContactDetails values

    (3, '[email protected]', '3333333333', '3333333333')InsertintoEmployeeContactDetails values

    (4, '[email protected]', '44444444444', '44444444444')

    InsertintoEmployeeContactDetails values

    (5, '[email protected]', '5555555555', '5555555555')

    Step 16:At this point run the application. Insert, update and delete an Employee, and notice that

    both the tables (Employees and EmployeeContactDetails) are updated as expected.

  • 8/10/2019 Entity Framework Video Content

    42/61

    Part 12 - Table splitting in entity framework

    Suggested Videos

    Part 9 - Overriding stored procedure defaults with entity frameowrk code first approach

    Part 10 - Entity splitting in entity framework

    Part 11 - Entity splitting in entity framework with code first approach

    In this video we will discuss Table splitting in entity framework with database first approach.

    Table Splitting is the opposite of Entity Splitting.

    We discussed Entity Splitting inPart 10and11ofEntity Framework tutorial.

    Entity Splittingrefers to mapping an entity to two or more tables when the tables share a

    common key.

    Mapping multiple entities to a single table is called table splitting .

    http://csharp-video-tutorials.blogspot.com/2014/05/part-9-overriding-stored-procedure.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-9-overriding-stored-procedure.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-10-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-10-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-11-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-11-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-10-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-10-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-10-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-11-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-11-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-11-entity-splitting-in-entity.htmlhttps://www.youtube.com/playlist?list=PL6n9fhu94yhUPBSX-E2aJCnCR3-_6zBZxhttps://www.youtube.com/playlist?list=PL6n9fhu94yhUPBSX-E2aJCnCR3-_6zBZxhttps://www.youtube.com/playlist?list=PL6n9fhu94yhUPBSX-E2aJCnCR3-_6zBZxhttps://www.youtube.com/playlist?list=PL6n9fhu94yhUPBSX-E2aJCnCR3-_6zBZxhttp://csharp-video-tutorials.blogspot.com/2014/05/part-11-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-10-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-11-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-10-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-9-overriding-stored-procedure.html
  • 8/10/2019 Entity Framework Video Content

    43/61

    One common entity framework interview question is, What is the main reason for using Table

    Splitting?

    Table Splitting is useful when you want to delay the loading of some properties with large data

    when using lazy loading.

    For example, if you have Employee entity and if it contains Photo property that would return large

    binary data, and if we use this Photo property only on a few pages in our application, then it does

    not make sense from a performance perspective to load this property every time we load the

    Employee entity. Using lazy loading load it only on the pages where we need to display Employee

    photo.

    We will be using the following Employees table

    SQL script to create the table

    CreatetableEmployees

    (

    EmployeeID intprimarykeyidentity,

    FirstName nvarchar(50),

    LastName nvarchar(50),Gender nvarchar(50),

  • 8/10/2019 Entity Framework Video Content

    44/61

    Email nvarchar(50),

    Mobile nvarchar(50),

    LandLine nvarchar(50)

    )

    InsertintoEmployees values ('Mark', 'Hastings', 'Male', '[email protected]', 'XXX', 'XXX')

    InsertintoEmployees values ('Steve', 'Pound', 'Male', '[email protected]', 'YYY', 'YYY')

    InsertintoEmployees values ('Ben', 'Hoskins', 'Male', '[email protected]', 'ZZZ', 'ZZZ')

    InsertintoEmployees values ('Philip', 'Hastings', 'Male', '[email protected]', 'AAA', 'AAA')

    InsertintoEmployees values ('Mary', 'Lambeth', 'Female', '[email protected]', 'BBB', 'BBB')

    Now, when we use ADO.NET Entity Framework to generate entities from the database using

    database first approach, by default one entity will be created, i.e Empoyee entity.

    Let's say, we will not be using Email, Mobile and Landline properties as often as we would be

    using FirstName, LastName, and Gender properties. If all of these properties are present in one

    Employee entity, then every time we load this entity, all the properties will be automatically

    loaded. So let's create 2 entities (Employee & EmployeeContactDetail). This enables us to load

    EmployeeContactDetails only when needed.

    To achieve this:

    1.Right click on the entity designer and select "Add Entity" option from the context menu. Set

    a)Entity Name = EmployeeContactDetail

    b)Bae type = (None)c)Entity Set = EmployeeContactDetails

    d)Create Key Property = Checked

    e)Property Name = EmployeeID

  • 8/10/2019 Entity Framework Video Content

    45/61

    2.Cut Email, Mobile and LandLine properties from Employee entity and paste them in

    EmployeeContactDetail entity

    3.Right click on the entity designer and select "Add - Association" option from the context menu.

    Fill the details shown below.

  • 8/10/2019 Entity Framework Video Content

    46/61

    4.Right click on the association and select "Properties". In the Properties window, click on the

    ellipsis button next to "Referential Constraint" property and fill in the details as shown below.

    5.Right click on "EmployeeContactDetail" entity and select "Table Mapping" option from the

  • 8/10/2019 Entity Framework Video Content

    47/61

    context menu. Select "Employees" table and map EmployeeId, Email, Mobile andLandline

    properties of the entity to the respective columns of the table.

    6.Add a webform. Copy and paste the following HTML in the ASPX page.

    7.Copy and paste the following code in the code-behind file.

    publicpartialclassWebForm1: System.Web.UI.Page

    {

    privateDataTableGetEmployeeData()

    {

    EmployeeDBContextemployeeDBContext = newEmployeeDBContext();

    List employees = employeeDBContext.Employees.ToList();

    DataTabledataTable = newDataTable();DataColumn[] columns = { newDataColumn("EmployeeID"),

    newDataColumn("FirstName"),

    newDataColumn("LastName"),

    newDataColumn("Gender")};

    dataTable.Columns.AddRange(columns);

    foreach(Employeeemployee inemployees)

    {

    DataRowdr = dataTable.NewRow();dr["EmployeeID"] = employee.EmployeeID;

  • 8/10/2019 Entity Framework Video Content

    48/61

    dr["FirstName"] = employee.FirstName;

    dr["LastName"] = employee.LastName;

    dr["Gender"] = employee.Gender;

    dataTable.Rows.Add(dr);

    }

    returndataTable;

    }

    privateDataTableGetEmployeeDataIncludingContactDetails()

    {

    EmployeeDBContextemployeeDBContext = newEmployeeDBContext();

    List employees = employeeDBContext.Employees

    .Include("EmployeeContactDetail").ToList();

    DataTabledataTable = newDataTable();

    DataColumn[] columns = { newDataColumn("EmployeeID"),

    newDataColumn("FirstName"),

    newDataColumn("LastName"),

    newDataColumn("Gender"),

    newDataColumn("Email"),

    newDataColumn("Mobile"),

    newDataColumn("LandLine") };

    dataTable.Columns.AddRange(columns);

    foreach(Employeeemployee inemployees)

    {

    DataRowdr = dataTable.NewRow();

    dr["EmployeeID"] = employee.EmployeeID;

    dr["FirstName"] = employee.FirstName;

    dr["LastName"] = employee.LastName;

    dr["Gender"] = employee.Gender;

    dr["Email"] = employee.EmployeeContactDetail.Email;

    dr["Mobile"] = employee.EmployeeContactDetail.Mobile;

    dr["LandLine"] = employee.EmployeeContactDetail.LandLine;

    dataTable.Rows.Add(dr);

    }

    returndataTable;

    }

    protectedvoidButton1_Click(objectsender, EventArgse)

    {

    if(checkBoxIncludeContactDetails.Checked){

  • 8/10/2019 Entity Framework Video Content

    49/61

    GridView1.DataSource = GetEmployeeDataIncludingContactDetails();

    }

    else

    {

    GridView1.DataSource = GetEmployeeData();

    }

    GridView1.DataBind();

    }

    }

    At this point, run the application and when you retrieve Employees without checking "Include

    Contact Details" checkbox, the following query is generated by the entity framework. Use SQL

    Profilerto view the generated query. Notice that Email, Mobile and LandLine column values are

    not loaded.

    SELECT

    [Extent1].[EmployeeID] AS[EmployeeID],[Extent1].[FirstName] AS[FirstName],

    [Extent1].[LastName] AS[LastName],

    [Extent1].[Gender] AS[Gender]

    FROM[dbo].[Employees] AS[Extent1]

    When you check "Include Contact Details" checkbox, the following query is generated

    SELECT

    [Extent1].[EmployeeID] AS[EmployeeID],

    [Extent1].[FirstName] AS[FirstName],

    [Extent1].[LastName] AS[LastName],[Extent1].[Gender] AS[Gender],

    [Extent1].[Email] AS[Email],

    [Extent1].[Mobile] AS[Mobile],

    [Extent1].[LandLine] AS[LandLine]

    FROM[dbo].[Employees] AS[Extent1]

  • 8/10/2019 Entity Framework Video Content

    50/61

    Part 13 - Table splitting in entity framework with code first approach

    Suggested Videos

    Part 10 - Entity splitting in entity framework

    Part 11 - Entity splitting in entity framework with code first approach

    Part 12 - Table splitting in entity framework

    In this video we will discuss Table splitting in entity framework with code first approach. We

    discussed Table Splitting with database first approach inPart 12.

    Mapping multiple entities to a single table is called table splitting .

    Step 1:Create a new empty asp.net web application project. Name it Demo. Install entity

    framework if it's not already installed.

    Step 2: Add a class file to the project. Name it Employee.cs. Copy and paste the following code.namespaceDemo

    {

    publicclassEmployee

    {

    publicintEmployeeID { get; set; }

    publicstringFirstName { get; set; }

    publicstringLastName { get; set; }

    publicstringGender { get; set; }

    publicEmployeeContactDetailEmployeeContactDetail { get; set; }}

    }

    Step 3:Add a class file to the project. Name it EmployeeContactDetail.cs. Copy and paste the

    following code.

    namespaceDemo

    {

    publicclassEmployeeContactDetail

    {

    publicintEmployeeID { get; set; }publicstringEmail { get; set; }

    publicstringMobile { get; set; }

    publicstringLandLine { get; set; }

    publicEmployeeEmployee { get; set; }

    }

    }

    Step 4:Add a class file to the project. Name it EmployeeDBContext.cs. Copy and paste the

    following code.usingSystem.Data.Entity;

    http://csharp-video-tutorials.blogspot.com/2014/05/part-10-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-10-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-11-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-11-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-12-table-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-12-table-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-12-table-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-12-table-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-12-table-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-12-table-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-12-table-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-11-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-10-entity-splitting-in-entity.html
  • 8/10/2019 Entity Framework Video Content

    51/61

    namespaceDemo

    {

    publicclassEmployeeDBContext: DbContext

    {

    publicDbSet Employees { get; set; }

    protectedoverridevoidOnModelCreating(DbModelBuildermodelBuilder)

    {

    modelBuilder.Entity()

    .HasKey(pk => pk.EmployeeID)

    .ToTable("Employees");

    modelBuilder.Entity()

    .HasKey(pk => pk.EmployeeID)

    .ToTable("Employees");

    modelBuilder.Entity()

    .HasRequired(p => p.EmployeeContactDetail)

    .WithRequiredPrincipal(c => c.Employee);

    }

    }

    }

    Step 5:Add the database connection string in web.config file.

    Step 6:Add a web form to the project. Copy and paste the following HTML in the aspx page

    Step 7:Copy and paste the following code in the code-behind file.

    publicpartialclassWebForm1: System.Web.UI.Page

    {

    privateDataTable GetEmployeeData()

    {EmployeeDBContext employeeDBContext = newEmployeeDBContext();

  • 8/10/2019 Entity Framework Video Content

    52/61

    List employees = employeeDBContext.Employees.ToList();

    DataTable dataTable = newDataTable();

    DataColumn[] columns = { newDataColumn("EmployeeID"),

    newDataColumn("FirstName"),

    newDataColumn("LastName"),

    newDataColumn("Gender")};

    dataTable.Columns.AddRange(columns);

    foreach(Employee employee inemployees)

    {

    DataRow dr = dataTable.NewRow();

    dr["EmployeeID"] = employee.EmployeeID;

    dr["FirstName"] = employee.FirstName;

    dr["LastName"] = employee.LastName;dr["Gender"] = employee.Gender;

    dataTable.Rows.Add(dr);

    }

    returndataTable;

    }

    privateDataTable GetEmployeeDataIncludingContactDetails()

    {EmployeeDBContext employeeDBContext = newEmployeeDBContext();

    List employees = employeeDBContext.Employees

    .Include("EmployeeContactDetail").ToList();

    DataTable dataTable = newDataTable();

    DataColumn[] columns = { newDataColumn("EmployeeID"),

    newDataColumn("FirstName"),

    newDataColumn("LastName"),

    newDataColumn("Gender"),

    newDataColumn("Email"),newDataColumn("Mobile"),

    newDataColumn("LandLine") };

    dataTable.Columns.AddRange(columns);

    foreach(Employee employee inemployees)

    {

    DataRow dr = dataTable.NewRow();

    dr["EmployeeID"] = employee.EmployeeID;

    dr["FirstName"] = employee.FirstName;

    dr["LastName"] = employee.LastName;dr["Gender"] = employee.Gender;

  • 8/10/2019 Entity Framework Video Content

    53/61

    dr["Email"] = employee.EmployeeContactDetail.Email;

    dr["Mobile"] = employee.EmployeeContactDetail.Mobile;

    dr["LandLine"] = employee.EmployeeContactDetail.LandLine;

    dataTable.Rows.Add(dr);

    }

    returndataTable;

    }

    protectedvoidButton1_Click(objectsender, EventArgs e)

    {

    if(checkBoxIncludeContactDetails.Checked)

    {

    GridView1.DataSource = GetEmployeeDataIncludingContactDetails();

    }

    else{

    GridView1.DataSource = GetEmployeeData();

    }

    GridView1.DataBind();

    }

    }

    At this point, run the application. Sample database and Employees table should be created by the

    entity framework.

    Step 8: Insert test data using the following SQL script

    InsertintoEmployees values ('Mark', 'Hastings', 'Male', '[email protected]', 'XXX', 'XXX')

    InsertintoEmployees values ('Steve', 'Pound', 'Male', '[email protected]', 'YYY', 'YYY')

    InsertintoEmployees values ('Ben', 'Hoskins', 'Male', '[email protected]', 'ZZZ', 'ZZZ')

    InsertintoEmployees values ('Philip', 'Hastings', 'Male', '[email protected]', 'AAA', 'AAA')

    InsertintoEmployees values ('Mary', 'Lambeth', 'Female', '[email protected]', 'BBB', 'BBB')

    When you retrieve Employees without checking "Include Contact Details" checkbox, the following

    query is generated by the entity framework. Use SQL Profile to view the generated query. Notice

    that Email, Mobile and LandLine column values are not loaded.SELECT

    [Extent1].[EmployeeID] AS[EmployeeID],

    [Extent1].[FirstName] AS[FirstName],

    [Extent1].[LastName] AS[LastName],

    [Extent1].[Gender] AS[Gender]

    FROM[dbo].[Employees] AS[Extent1]

    When you check "Include Contact Details" checkbox, the following query is generated

    SELECT

    [Extent1].[EmployeeID] AS[EmployeeID],[Extent1].[FirstName] AS[FirstName],

  • 8/10/2019 Entity Framework Video Content

    54/61

    [Extent1].[LastName] AS[LastName],

    [Extent1].[Gender] AS[Gender],

    [Extent1].[Email] AS[Email],

    [Extent1].[Mobile] AS[Mobile],

    [Extent1].[LandLine] AS[LandLine]

    FROM[dbo].[Employees] AS[Extent1]

    Part 14 - Conditional Mapping in entity framework

    Suggested Videos

    Part 11 - Entity splitting in entity framework with code first approach

    Part 12 - Table splitting in entity framework

    Part 13 - Table splitting in entity framework with code first approach

    In this video we will discuss Conditional Mapping feature in entity framework with database first

    approach. Let us understand what Conditional Mapping can do with an example.

    We will be using the following Employees table in this demo. IsTerminated column determines if

    an employee is a terminated employee or not.

    SQL Query to create Employees table

    CreatetableEmployees

    (

    EmployeeID intprimarykeyidentity,

    FirstName nvarchar(50),

    LastName nvarchar(50),

    Gender nvarchar(50),

    IsTerminated bitnot null

    )

    GO

    InsertintoEmployees values ('Mark', 'Hastings', 'Male', 0)

    InsertintoEmployees values ('Steve', 'Pound', 'Male', 0)

    InsertintoEmployees values ('Ben', 'Hoskins', 'Male', 0)

    InsertintoEmployees values ('Philip', 'Hastings', 'Male', 1)

    InsertintoEmployees values ('Mary', 'Lambeth', 'Female', 0)

    InsertintoEmployees values ('Valarie', 'Vikings', 'Female', 0)

    InsertintoEmployees values ('John', 'Stanmore', 'Male', 1)

    http://csharp-video-tutorials.blogspot.com/2014/05/part-11-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-11-entity-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-12-table-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-12-table-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-13-table-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-13-table-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-13-table-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-12-table-splitting-in-entity.htmlhttp://csharp-video-tutorials.blogspot.com/2014/05/part-11-entity-splitting-in-entity.html
  • 8/10/2019 Entity Framework Video Content

    55/61

    If the application that we are developing always need only the employees who are not

    terminated, then in the query we will have to always include the filter across our entire

    application. Conditional Mappingcan be used to apply such a permanent filter on the entity, so

    that the generated SQL query always have the WHERE clause.

    To use Conditional Mapping,

    1.Right click on the entity and select "Table Mapping" option from the context menu

    2.Add the condition - When Is Terminated = false

    At this point, if you build the solution or validate the model, you will get the following error

    Problem in mapping fragments starting at line 46:Condition member 'Employees.IsTerminated'

    with a condition other than 'IsNull=False' is mapped. Either remove the condition on

    Employees.IsTerminated or remove it from the mapping

    This is because, a table column cannot be mapped more than once. We have used IsTerminated

    column in conditional mapping, so it cannot be used in property mapping as well. For this reason

    delete it from Employee entity.

    Add a web form to the project. Drag and drop a GridView control. Copy and paste the following

    code in the code-behind file.

    protectedvoidPage_Load(objectsender, EventArgse)

    {

    EmployeeDBContextemployeeDBContext=newEmployeeDBContext();

    GridView1.DataSource=employeeDBContext.Employees;GridView1.DataBind();

    }

    Open SQL profiler and run the webform. Notice that the select query has a where clause, which

    will always return employees who are not terminated.

    SELECT

    [Extent1].[EmployeeID] AS[EmployeeID],

    [Extent1].[FirstName] AS[FirstName],

    [Extent1].[LastName] AS[LastName],

    [Extent1].[Gender] AS[Gender]FROM[dbo].[Employees] AS[Extent1]

  • 8/10/2019 Entity Framework Video Content

    56/61

    WHERE[Extent1].[IsTerminated] = 0

    Part 15 - Conditional Mapping in entity framework with code first

    Suggested Videos

    Part 12 - Table splitting in entity framework

    Part 13 - Table splitting