Introduction to Entity Framework Part 1 Tom Perkins NTPCUG.

Slides:



Advertisements
Similar presentations
Stored procedures and views You can see definitions for stored procedures and views in the demo databases but you can’t change them. For views, expand.
Advertisements

Introduction to MVC Adding a View Page NTPCUG Tom Perkins, Ph.D.
Introduction to MVC Action Methods, Edit View, and a Search Feature NTPCUG Dr. Tom Perkins.
11 Getting Started with ASP.NET Beginning ASP.NET 4.0 in C# 2010 Chapters 5 and 6.
Part 03 – Sorting, Paging, and Grouping Entity Framework NTPCUG Tom Perkins.
Web Development in Microsoft Visual Studio Slide 2 Lecture Overview Introduce Visual Studio 2013 Create a first ASP.NET application.
Guide to Oracle10G1 Introduction To Forms Builder Chapter 5.
Chapter 12: ADO.NET and ASP.NET Programming with Microsoft Visual Basic.NET, Second Edition.
A Guide to Oracle9i1 Introduction To Forms Builder Chapter 5.
A Guide to Oracle9i1 Creating an Integrated Database Application Chapter 8.
Part 05 – Code First Migrations and Azure Deployment Entity Framework and MVC Series Tom Perkins NTPCUG.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Using ERWin to model your data Supplied by Computer Associates as part of AllFusion.
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
ORM Technologies and Entity Framework (EF)
® IBM Software Group © 2006 IBM Corporation The Eclipse Data Perspective and Database Explorer This section describes how to use the Eclipse Data Perspective,
5 Copyright © 2009, Oracle. All rights reserved. Defining ETL Mappings for Staging Data.
An Introduction to ASP.NET Web Pages 2 Module 1: Webmatrix Installation and Your First Web Site Tom Perkins.
2. Introduction to the Visual Studio.NET IDE 2. Introduction to the Visual Studio.NET IDE Ch2 – Deitel’s Book.
CONFIGURING WINDOWS SERVER MIS 424 Professor Sandvig.
McGraw-Hill© 2007 The McGraw-Hill Companies, Inc. All rights reserved. 1-1.
Tutorial: Introduction to ASP.NET Internet Technologies and Web Application 4 th February 2010.
Introduction to MVC Adding Model Classes NTPCUG Tom Perkins, Ph.D.
.NET Database Technologies: Entity Framework additional notes – part 2.
Databases and LINQ Visual Basic 2010 How to Program 1.
ASP.NET Programming with C# and SQL Server First Edition
Microsoft Visual Basic 2005: Reloaded Second Edition
BIT 286: Web Applications Lecture 04 : Thursday, January 15, 2015 ASP.Net MVC - Models.
Programming with Microsoft Visual Basic 2012 Chapter 12: Web Applications.
Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins.
10-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
Creating a Web Site to Gather Data and Conduct Research.
ASP.NET Web Application and Development Digital Media Department Unit Credit Value : 4 Essential Learning time : 120 hours Digital.
Tutorial 1: Browser Basics.
Part 04 – Preparing to Deploy to the Cloud Entity Framework and MVC Series Tom Perkins NTPCUG.
2. Introduction to the Visual Studio.NET IDE. Chapter Outline Overview of the Visual Studio.NET IDE Overview of the Visual Studio.NET IDE Menu Bar and.
11 Web Services. 22 Objectives You will be able to Say what a web service is. Write and deploy a simple web service. Test a simple web service. Write.
Introduction to ASP.NET MVC Information for this presentation was taken from Pluralsight Building Applications with ASP.NET MVC 4.
1 Data Bound Controls II Chapter Objectives You will be able to Use a Data Source control to get data from a SQL database and make it available.
1 Working with MS SQL Server Textbook Chapter 14.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Working with MSSQL Server Code:G0-C# Version: 1.0 Author: Pham Trung Hai CTD.
Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG.
CERN - IT Department CH-1211 Genève 23 Switzerland t DB Development Tools Benthic SQL Developer Application Express WLCG Service Reliability.
CSCI 6962: Server-side Design and Programming Database Manipulation in ASP.
BIT 285: ( Web) Application Programming Lecture 15: Tuesday, February 24, 2015 Microsoft Azure Instructor: Craig Duckett.
Entity Framework: Code First SoftUni Team Technical Trainers Software University
Introduction to MVC Introduction NTPCUG Tom Perkins, Ph.D.
Introduction to MVC Controllers NTPCUG Tom Perkins, Ph.D.
Ch. 101 Database Management An Introduction to Databases.
BlackBerry Applications using Microsoft Visual Studio and Database Handling.
All information's of PLINQO in this Document, I got it from: So, you could visit the link above to research.
Lecture Set 2 Part A: Creating an Application with Visual Studio – Solutions, Projects, Files 8/10/ :35 PM.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Address Book Application Introducing Database Programming.
11 Getting Started with ASP.NET Beginning ASP.NET in C# and VB Chapters 1 and 2.
CSCI 3327 Visual Basic Chapter 13: Databases and LINQ UTPA – Fall 2011.
11 User Controls Beginning ASP.NET in C# and VB Chapter 8.
Entity Framework Database Connection with ASP Notes from started/getting-started-with-ef-using-mvc/creating-an-
BIT 286: Web Applications Lecture 04 : Thursday, January 15, 2015 ASP.Net MVC -
BIT 286: Web Applications ASP.Net MVC. Objectives Applied MVC overview Controllers Intro to Routing Views ‘Convention over configuration’ Layout files.
1 Adding a Model. We have created an MVC web app project Added a controller class. Added a view class. Next we will add some classes for managing movies.
Jim Fawcett CSE686 – Internet Programming Spring 2014
ASP.NET Forms.
Visual Basic 2010 How to Program
Introduction to Entity Framework
Entity Framework DB From Code, OOP Introduction
Jim Fawcett CSE686 – Internet Programming Spring 2012
02 | Developing ASP.NET MVC 4 Models
C# - EF Core IT College, Andres Käver, , Fall semester
Security - Forms Authentication
Presentation transcript:

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: – started-with-ef-using-mvc

CONFIGURE YOUR COMPUTER Objective 1

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)

Azure SDK Required – the application will not compile without it Download the Web Platform Installer, then follow the instructions – This will take a while to download

Sample Screen

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

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.

CREATE THE CONTOSO UNIVERSITY WEBSITE Objective 2

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

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

Select the MVC Template Click Change Authentication

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

Run the project (F5)

SET UP THE SITE STYLE Objective 3

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

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

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

INSTALL ENTITY FRAMEWORK 6 Objective 4

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

Install EF

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.

CREATE THE DATA MODEL Objective 5 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.

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 folder Create a new class called Student.cs Replace the code with TimeSaver.docx Mod 3 ( on a following slide)

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 Enrollments { get; set; } } The Student Class (Replace default code)

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

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 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; } }

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

The Course Class using 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 Enrollments { get; set; } } Enrollments – navigation property – a course may have many enrollments DatabaseGenerated Attribute – you can set the primary key.

CREATE THE DATABASE CONTEXT (DATA ACCESS LAYER) Objective 6

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.

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

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 Students { get; set; } public DbSet Enrollments { get; set; } public DbSet Courses { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove (); }

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

SET UP EF TO CREATE TEST DATA Objective 7

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

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

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 { protected override void Seed(SchoolContext context) { var students = new List { new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse(" ")}, new Student{FirstMidName="Meredith",LastName="Alonso",EnrollmentDate=DateTime.Parse(" ")}, new Student{FirstMidName="Arturo",LastName="Anand",EnrollmentDate=DateTime.Parse(" ")}, new Student{FirstMidName="Gytis",LastName="Barzdukas",EnrollmentDate=DateTime.Parse(" ")}, new Student{FirstMidName="Yan",LastName="Li",EnrollmentDate=DateTime.Parse(" ")}, new Student{FirstMidName="Peggy",LastName="Justice",EnrollmentDate=DateTime.Parse(" ")}, …

Tell EF to Use the Initializer on Entry Add Mod 8 to Web.config file (in the root project folder...

SET UP EF TO USE A SQL SERVER EXPRESS LOCALDB DATABASE Objective 8

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

Working with LocalDB Open the (root) Web.config file. Add Modification 9 just prior to the element EF will use LocalDB ContosoUniversity1.mdf EF will create this database

Code for Connection String

CREATE STUDENT CONTROLLER AND VIEWS Objective 9

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.

Build a new controller 1.Right-click on the Controllers folder in the Solution Explorer. 2.Select Add. 3.Select New Scaffolded Item.

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

Controller name: StudentController Model Class: Student (ContosoUniversity.Models) Data context class: SchoolContext(ContosoUniversity.DAL) Leave other defaults as-is. Click Add

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

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.

VIEW THE DATABASE Objective 10

The SQL Database When you tried to access the data, EF saw there was no database Generated the database Ran the seed method populate the data. 1.Close the browser. 2.In Server Explorer 1.Expand Data Connections 2.Expand School Context (Contoso University) 3.Expand Tables (to see the database).

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

REVIEW “CONVENTIONS” Objective 11

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 Foreign Key properties – Derived from

Next – Really getting into CRUD FINIS