1 / 62

Introduction to Entity Framework Part 1

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

vila
Télécharger la présentation

Introduction to Entity Framework Part 1

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Entity FrameworkPart 1 Tom Perkins NTPCUG

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

  3. Objective 1 Configure your computer

  4. 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)

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

  6. Sample Screen

  7. Part 1 Walkthru Objectives • Configuration, including Azure SDK • Create Contoso University C# Web Project • Set up the site style • Install Entity Framework 6 • Build the Data Model • Create the Database Context (Data Access Layer) • Set up EF to Create Test Data • Connect to LocalDB • Create a Student Controller and Views • View the Database • Review EF Conventions

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

  9. Objective 2 Create the contoso university website

  10. Create the Contoso University Website • Open VS 2013 (or whatever) • Click File | New | Project • Enter ContosoUniversity

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

  12. Select the MVC Template • Click Change Authentication

  13. Select No Authentication • Click OK • In the ASP.NET Project Dialog Box • Click OK to create the project

  14. Run the project (F5)

  15. Objective 3 Set up the site style

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

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

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

  19. Objective 4 Install entity framework 6

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

  21. Install EF

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

  23. Objective 5 CREATE THE DATA MODEL 3 Entity Classes: Course, Enrollment, Student Course to Enrollment: One to Many Relationship Student to Enrollment: One to Many Relationship We’ll create one class per entity.

  24. Create the Student Entity In the Models folder Create a new class called Student.cs Replace the code with TimeSaver.docx Mod 3 ( on a following slide) • ID • Becomes primary key of database table for class • EF interprets ID or classnameIDas 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.

  25. The Student Class (Replace default code) 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 DateTimeEnrollmentDate { get; set; } public virtual ICollection<Enrollment> Enrollments { get; set; } } }

  26. Create the Enrollment Class In the Models folder, create the Enrollment.cs class. Replace the existing code with TimeSaver.docx – Mod 4

  27. The Enrollment Class namespace ContosoUniversity.Models { public enum Grade { A, B, C, D, F } public class Enrollment { public intEnrollmentID { get; set; } public intCourseID { get; set; } public intStudentID { get; set; } public Grade? Grade { get; set; } public virtual Course Course { get; set; } public virtual Student Student { get; set; } } } • 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>

  28. The Course Entity In the Models folder create the Course Class Replace the generated code with TimeSaver.cs – Mod 5

  29. The Course Class using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; namespace ContosoUniversity.Models { public class Course { [DatabaseGenerated(DatabaseGeneratedOption.None)] public intCourseID { 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 enrollments DatabaseGenerated Attribute – you can set the primary key.

  30. Objective 6 Create the Database Context (Data Access Layer)

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

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

  33. 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(DbModelBuildermodelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } } }

  34. Notes for Database Context class • 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.Removestatement • If not present, generated table names would be plural • Students, Courses, etc.

  35. Objective 7 Set up EF to Create Test Data

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

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

  38. 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")}, …

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

  40. Objective 8 Set up EF to use a SQL Server Express LocalDB database

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

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

  43. Code for Connection String

  44. Objective 9 Create student controller and views

More Related