introduction to entity framework part 1 tom perkins ntpcug

62
Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Upload: phyllis-baldwin

Post on 21-Dec-2015

228 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Introduction to Entity FrameworkPart 1

Tom PerkinsNTPCUG

Page 2: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Walkthru Overview

• We plan to construct a simple website for Contoso University

• Users can enter and update student, instructor and course information.

• We will use Entity Framework 6 and MVC 5• The hand-on walkthru will follow the

Microsoft tutorial:– http://www.asp.net/mvc/tutorials/getting-started-

with-ef-using-mvc

Page 3: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

CONFIGURE YOUR COMPUTERObjective 1

Page 4: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Prerequisites

• Visual Studio 2013 or Visual Studio 2012 or Visual Studio 2013 Express for Web

• .NET 5• Entity Framework 6 (installed during course)• Windows Azure SDK 2.2 (required)

Page 5: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Azure SDK

• Required – the application will not compile without it

• Download the Web Platform Installer, then follow the instructions– http://www.windowsazure.com/en-us/downloads

• This will take a while to download

Page 6: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Sample Screen

Page 7: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG
Page 8: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Part 1 Walkthru Objectives

1. Configuration, including Azure SDK2. Create Contoso University C# Web Project3. Set up the site style4. Install Entity Framework 65. Build the Data Model6. Create the Database Context (Data Access Layer)7. Set up EF to Create Test Data8. Connect to LocalDB9. Create a Student Controller and Views10. View the Database11. Review EF Conventions

Page 9: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

The TimeSaver .docx File

• Some of the steps in the walkthru involve a fair amount of typing.

• The TimeSaver .docx file includes snippets that can be pasted over a default file created by the system.

Page 10: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

CREATE THE CONTOSO UNIVERSITY WEBSITE

Objective 2

Page 11: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Create the Contoso University Website

• Open VS 2013 (or whatever)• Click File | New | Project• Enter ContosoUniversity

Page 12: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

• Name: ContosoUniversity• Select ASP.NET Web Application• Select file location (C:\)• Click OK

Page 13: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

• Select the MVC Template• Click Change Authentication

Page 14: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

• Select No Authentication• Click OK• In the ASP.NET Project Dialog Box

• Click OK to create the project

Page 15: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Run the project (F5)

Page 16: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG
Page 17: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

SET UP THE SITE STYLEObjective 3

Page 18: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Change the Master Layout• Open Views\Shared\

_Layout.cshtml• Change “My ASP.NET

Application” and “Application Name” to “Contoso University”

• Add menu entries for – Students– Courses– Instructors– Departments

See TimeSaver.docx Mod 1

Page 19: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG
Page 20: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

MVC Concepts

• ViewBag:– The ViewBag property enables you to dynamically share values

from the controller to the view. It is a dynamic object which means it has no pre-defined properties. You define the properties you want the ViewBag to have by simply adding them to the property. In the view, you retrieve those values by using same name for the property.

• ActionLink – returns the virtual path of the specified action – Parameters– Text for Link– Action Name– Controller Name

Page 21: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Views\Home\Index.cshtml• Replace the contents of

Views\Home\Index.cshtml with TimeSaver.docx – Modification 2

• Read through the contents of Views\Home\Index.cshtml

• Press CTRL + F5 to run the site

Page 22: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG
Page 23: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

INSTALL ENTITY FRAMEWORK 6Objective 4

Page 24: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Install most recent EF 6

• Select Tools\LibraryPackageManager\PackageManagerConsole

• At the PM> prompt, type “Install-Package EntityFramework”

• Note that Entity Framework is added to the application

Page 25: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Install EF

Page 26: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Automatic Install

• The scaffolding feature can automatically install EF

• It will automatically – install the EF NuGet feature– Create the database context class– Create the connection string

• This was done manually in this tutorial to see the steps involved.

Page 27: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

CREATE THE DATA MODELObjective 5

3 Entity Classes: Course, Enrollment, StudentCourse to Enrollment: One to Many RelationshipStudent to Enrollment: One to Many Relationship

We’ll create one class per entity.

Page 28: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Create the Student Entity

• ID – Becomes primary key of database table for class– EF interprets ID or classnameID as primary key

• Enrollments – Navigation Property– Holds other entities related to this property– Student’s entity Enrollments (plural) property contains references to all the

Enrollment entities for that student– Defined as virtual – allows lazy loading – Type must be a list that allows updating, deleting, adding, -- such as Icollection.

In the Models folderCreate a new class called Student.cs

Replace the code with TimeSaver.docx Mod 3 ( on a following slide)

Page 29: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG
Page 30: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG
Page 31: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

using System;using System.Collections.Generic;

namespace ContosoUniversity.Models{ public class Student { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } }}

The Student Class (Replace default code)

Page 32: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Create the Enrollment ClassIn the Models folder,

create the Enrollment.cs class.Replace the existing code with TimeSaver.docx – Mod 4

Page 33: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

The Enrollment Class• EnrollmentID – creates primary key

– Note different pattern• Grade property – enum

– ? Indicates nullable

• StudentID – foreign key• Navigation property is Student

– Contains single Student entity– Not multiples as before

• CourseID – foreign key• Navigation property is Course

– Contains single Course entity– Not multiples as before

• EF identifies foreign key properties if it’s named <navigation key property name><primary key property name>

namespace ContosoUniversity.Models{ public enum Grade { A, B, C, D, F }

public class Enrollment { public int EnrollmentID { get; set; } public int CourseID { get; set; } public int StudentID { get; set; } public Grade? Grade { get; set; } public virtual Course Course { get; set; } public virtual Student Student { get; set; } }}

Page 34: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

The Course EntityIn the Models folder

create the Course ClassReplace the generated code with TimeSaver.cs – Mod 5

Page 35: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

The Course Classusing System.Collections.Generic;using System.ComponentModel.DataAnnotations.Schema;

namespace ContosoUniversity.Models{ public class Course { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int CourseID { get; set; } public string Title { get; set; } public int Credits { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } }}

Enrollments – navigation property – a course may have many enrollmentsDatabaseGenerated Attribute – you can set the primary key.

Page 36: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

CREATE THE DATABASE CONTEXT (DATA ACCESS LAYER)

Objective 6

Page 37: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Database Context Class

• This is the main class that provides EF functionality for a given data model.

• You derive this class from the System.Data.Entity.DbClass.

• You specify which entities are included in the data model.

• You can customize EF behavior here.• In this project, the class is called SchoolContext.

Page 38: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Create the Database Context Class

• Right-click the ContosoUniversity project in the Solution Explorer.

• Click Add, then New Folder• Name the new folder DAL (for Data Access

Layer)• In the DAL folder, create a new class named

SchoolContext.cs• Replace the template code with TimeSaver.docx

– Modification 6

Page 39: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Code for SchoolContext.cs

using ContosoUniversity.Models;using System.Data.Entity;using System.Data.Entity.ModelConfiguration.Conventions;

namespace ContosoUniversity.DAL{ public class SchoolContext : DbContext { public SchoolContext() : base("SchoolContext") { } public DbSet<Student> Students { get; set; } public DbSet<Enrollment> Enrollments { get; set; } public DbSet<Course> Courses { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } }}

Page 40: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

• Specifying Entity Sets– A DbSet for each entity– Entity Set corresponds to a database table– Entity corresponds to a row in the table

• Connection String name– (“SchoolContext”) - Passed to constructor for class

• modelBuilder.Conventions.Remove statement– If not present, generated table names would be plural– Students, Courses, etc.

Notes for Database Context class

Page 41: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

SET UP EF TO CREATE TEST DATAObjective 7

Page 42: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Initialize with Test Data

• When application runs, EF can– Create a database– Drop and Create a database

• Specify– Every time– Or when model is out of sync with existing database

• Seed method– Called to repopulate database when EF runs

• Dropping database causes loss of all data– In development, use Seed() method to repopulate– In production, use Code First migrations whenever schema changes

Page 43: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Create Initializer Class

• In DAL folder– Create a new class called SchoolInitializer.cs– Causes database to be created– Loads database with test data– Replace generated code with TimeSaver – Mod 7

Page 44: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

School Initializer Class (partial)using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Data.Entity;using ContosoUniversity.Models;

namespace ContosoUniversity.DAL{ public class SchoolInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<SchoolContext> { protected override void Seed(SchoolContext context) { var students = new List<Student> { new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2005-09-01")}, new Student{FirstMidName="Meredith",LastName="Alonso",EnrollmentDate=DateTime.Parse("2002-09-01")}, new Student{FirstMidName="Arturo",LastName="Anand",EnrollmentDate=DateTime.Parse("2003-09-01")}, new Student{FirstMidName="Gytis",LastName="Barzdukas",EnrollmentDate=DateTime.Parse("2002-09-01")}, new Student{FirstMidName="Yan",LastName="Li",EnrollmentDate=DateTime.Parse("2002-09-01")}, new Student{FirstMidName="Peggy",LastName="Justice",EnrollmentDate=DateTime.Parse("2001-09-01")},

Page 45: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Tell EF to Use the Initializer on Entry

• Add Mod 8 to Web.config file (in the root project folder

<entityFramework> <contexts> <context type="ContosoUniversity.DAL.SchoolContext, ContosoUniversity"> <databaseInitializer type="ContosoUniversity.DAL.SchoolInitializer, ContosoUniversity" /> </context> </contexts> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"> <parameters>

. . .</providers></entityFramework>

Page 46: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

SET UP EF TO USE A SQL SERVER EXPRESS LOCALDB DATABASE

Objective 8

Page 47: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

LocalDB

• Lightweight version of SQL Server Express• Starts on demand, runs in user mode• Works with .mdf files• LocalDB files in App_Data folder can be

deployed with the project• Not to be used for production web

applications

Page 48: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Working with LocalDB

• Open the (root) Web.config file.• Add Modification 9 just prior to the

<appsettings> element• EF will use LocalDB ContosoUniversity1.mdf• EF will create this database

Page 49: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Code for Connection String

<connectionStrings>

<add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=ContosoUniversity1;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>

</connectionStrings>

Page 50: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

CREATE STUDENT CONTROLLER AND VIEWS

Objective 9

Page 51: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Student Controller and Views

• Objective: Display the Student data• A request for data automatically triggers the

dropping and re-creation of the Code First database.– The test data tables will be initialized.

• First step – a new controller.• Build the project.– Makes the model and context classes available to

the MVC controller scaffolding.

Page 52: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Build a new controller

1. Right-click on the Controllers folder in the Solution Explorer.

2. Select Add.3. Select New Scaffolded Item.

Page 53: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Select MVC5 Controller with views, using Entity Framework.Press Add.

Page 54: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Controller name: StudentControllerModel Class: Student (ContosoUniversity.Models)Data context class: SchoolContext(ContosoUniversity.DAL)

Leave other defaults as-is.Click Add

Page 55: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Scaffolding - Definition

The term “Scaffolding” is used by many software technologies to mean “quickly generating a basic outline of your software that you can then edit and customise”.

- Generated Code- Contains basic requirements- Can be edited and customized

Page 56: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Controllers\StudentController.cs… walkthru …

A class variable contains an instantiated database context object.

private SchoolContext db = new SchoolContext();

Index Action:- gets a list of students from the Students property in the database

context instance (db).- the list of students is passed to the Students\Index.cshtml view. The

view will render the list in HTML.

Students\Index.cshtml displays the list in a table – examine the code for this.

Run the project (CTRL + F5) and view the Students link.

Page 57: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

VIEW THE DATABASEObjective 10

Page 58: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

The SQL DatabaseWhen you tried to access the data,

EF saw there was no databaseGenerated the databaseRan the seed method populate the data.

1. Close the browser.2. In Server Explorer

1. Expand Data Connections2. Expand School Context (Contoso University)3. Expand Tables (to see the database).

Page 59: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Viewing the Database3. Right-click the Students table, then click Show Table Data.

Page 60: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

REVIEW “CONVENTIONS”Objective 11

Page 61: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Some EF Conventions

• Database table names– Derived from the pluralized form of the Entity classes.

• Database column names– Derived from Entity property names.

• Primary Key properties – Derived from entity property names ID or

<classnameID>• Foreign Key properties– Derived from <navigation property name><primary key

property name>

Page 62: Introduction to Entity Framework Part 1 Tom Perkins NTPCUG

Next – Really getting into CRUD

FINIS