Further exploring database operations in MVC Jim Warren, COMPSCI 280 S2 2014 Enterprise Software Development.

Slides:



Advertisements
Similar presentations
JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
Advertisements

CC SQL Utilities.
Introduction to MVC Adding a View Page NTPCUG Tom Perkins, Ph.D.
Further exploring the View aspect of MVC Jim Warren, COMPSCI 280 S Enterprise Software Development.
Introduction to MVC Action Methods, Edit View, and a Search Feature NTPCUG Dr. Tom Perkins.
Connecting an MVC application to a database Jim Warren, COMPSCI 280 S Enterprise Software Development.
1 Creating and Tweaking Data HRP223 – 2010 October 24, 2011 Copyright © Leland Stanford Junior University. All rights reserved. Warning: This.
A Guide to SQL, Seventh Edition. Objectives Create a new table from an existing table Change data using the UPDATE command Add new data using the INSERT.
U:/msu/course/cse/103 Day 23, Slide 1 Review of Day 22 What query did you use to search for an actor by name? –Return matches.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Chapter 14: Advanced Topics: DBMS, SQL, and ASP.NET
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
ORM Technologies and Entity Framework (EF)
MIS2502: Data Analytics MySQL and SQL Workbench David Schuff
Figure 1. Hit analysis in 2002 of database-driven web applications Hits by Category in 2002 N = 73,873 Results Reporting 27% GME 26% Research 20% Bed Availability.
Database Constraints. Database constraints are restrictions on the contents of the database or on database operations Database constraints provide a way.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
CHAPTER 9 DATABASE MANAGEMENT © Prepared By: Razif Razali.
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
Session 5: Working with MySQL iNET Academy Open Source Web Development.
Connecting a.NET application to a database Jim Warren, COMPSCI 280 S Enterprise Software Development.
BIT 286: Web Applications Lecture 04 : Thursday, January 15, 2015 ASP.Net MVC - Models.
Copyright © 2001 by Wiley. All rights reserved. Chapter 10: Advanced Database Operations Revising Vintage Videos Setting RecordSource at run time DBGrid.
1 MySQL and phpMyAdmin. 2 Navigate to and log on (username: pmadmin)
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
Internet Forms and Database Bob Kisel Amgraf, Inc.
Chapter 15: Using LINQ to Access Data in C# Programs.
Dbwebsites 2.1 Making Database backed Websites Session 2 The SQL… Where do we put the data?
PHP meets MySQL.
Chapter 7 Working with Databases and MySQL PHP Programming with MySQL 2 nd Edition.
ASP.NET MVC applications in C# Jim Warren, COMPSCI 280 S Enterprise Software Development.
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.
Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG.
Further exploring database operations from C#/.NET Jim Warren, COMPSCI 280 S Enterprise Software Development.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
RDBMSSection Relational DBMS DATABASE DEVELOPMENT And Franchise Colleges By MANSHA NAWAZ.
XP 1 New Perspectives on XML Binding XML Data with Internet Explorer.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Enhancing Forms with OLE Fields, Hyperlinks, and Subforms – Project 5.
BIT 286: Web Applications Lecture 10 : Thursday, February 5, 2015 ASP.Net Form Submission.
DT228/3 Web Development Databases. Querying a database: Partial info Search engines, on-line catalogues often need to allow user to search a database.
Reference: “ASP.NET 2.0 Illustrated” by Alex Homer and Dave Sussman. -ch3 illustrated book
Introduction to a Database Defining a database Database window in Access The six items in window: Tables, Queries Forms, Reports, Macros, Modules.
BIT 286: Web Applications Lecture 04 : Thursday, January 15, 2015 ASP.Net MVC -
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 1: Introduction to IS2803 Rob Gleasure
Chapter 12© copyright Janson Industries Java Server Faces ▮ Explain the JSF framework ▮ SDO (service data objects) ▮ Facelets ▮ Pagecode classes.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Address Book Application Introducing Database Programming.
1 A Very Brief Introduction to Relational Databases.
Entity Framework Database Connection with ASP Notes from started/getting-started-with-ef-using-mvc/creating-an-
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
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.
Day 22, Slide 1 CSE 103 Day 22 Non-students: Please logout by 10:12. Students:
1 Section 1 - Introduction to SQL u SQL is an abbreviation for Structured Query Language. u It is generally pronounced “Sequel” u SQL is a unified language.
DAY 20: ACCESS CHAPTERS 5, 6, 7 Larry Reaves October 28,
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.
Chapter 12 Introducing Databases. Objectives What a database is and which databases are typically used with ASP.NET pages What SQL is, how it looks, and.
Jim Fawcett CSE686 – Internet Programming Spring 2014
ASP.NET Programming with C# and SQL Server First Edition
Introduction to Entity Framework
Jim Fawcett CSE686 – Internet Programming Spring 2012
SQL and SQL*Plus Interaction
Social Media And Global Computing Managing Databases with MVC
C#: ASP.NET MVC Overview
Database application MySQL Database and PhpMyAdmin
Data Structures and Database Applications Managing Databases with MVC
MVC Framework, in general.
Computer Science Projects Database Theory / Prototypes
Presentation transcript:

Further exploring database operations in MVC Jim Warren, COMPSCI 280 S Enterprise Software Development

Today’s learning objectives  To be able to query through a variety of approaches including sending SQL directly to the DBMS and via LINQ  To be able to write more advanced queries in the MVC context, including joining tables and mapping the result to the View  To be able to update the database from the MVC context COMPSCI 2802

Last lecture…  We introduced Language Integrated Query (LINQ)  In this case the return value is a collection of objects of a class we’ve already defined in the Model  Because we had said: public DbSet Employees { get; set; } and had defined the Employee class with property names exactly aligned to the columns of the DBMS table  And in the VIEW we had IEnumerable Handout 03COMPSCI 2803 using (EmployeesContext db = new EmployeesContext()) { var emp = from e in db.Employees where e.DateOfBirth.Year < 1975 select e; return View(emp.ToList()); }

Dealing with a Join  But what if we want to present the user with the result of a Join on two (or more) tables?  Say that there’s a ‘role’ table which maps ‘employee’ rows by their primary key IDnum to one or more job roles  And I want to present the user with the meaningful fields from SELECT * FROM employee,role WHERE employee.IDnum=role.Idnum; Handout 03COMPSCI 2804 employee role

Extending the model  In your.cs file in the Models directory  Add the new DbSet to the DbContext  And add a class definition matching the new table  Fine so far… but what’s the class of the Join result? Handout 03COMPSCI 2805 public class EmployeesContext : DbContext { public EmployeesContext() : base("MySqlConnection") { } public DbSet Employees { get; set; } public DbSet Roles { get; set; } } [Table("role")] public class EmpRole { [Key] public int jobnum { get; set; } public int IDnum { get; set; } public string Role { get; set; } }

The Join  In HomeController.cs we can use a LINQ query  Back in the model, we need to define this new class Handout 03COMPSCI 2806 var ourEmployees = from e in db.Employees from r in db.Roles where e.IDnum == r.IDnum orderby e.Surname select new EmpforGrid { IDnum = e.IDnum, Surname = e.Surname, GivenNames = e.GivenNames, YearOfBirth = e.DateOfBirth.Year, Role = r.Role}; public class EmpforGrid { public int IDnum {get; set;} public string Surname {get; set;} public string GivenNames {get; set;} public int YearOfBirth { get; set;} public string Role { get; set;} } Also perfectly good, and better use of the LINQ language, would be to replace the 2 nd FROM and the WHERE with: join r in db.Roles on e.IDnum equals r.IDnum

The View  In Index.cshtml (under Views/Home)  We define the model for the view as an enumerable collection of instances of the new IEnumerable  And we define the WebGrid itself Handout 03COMPSCI ViewBag.Title = "People"; WebGrid grid = new WebGrid(Model); } grid.Columns( grid.Column("IDnum","Employee ID"), grid.Column("Surname","Last Name"), grid.Column("GivenNames","Given Names"), grid.Column("YearOfBirth","Birth Year"), grid.Column("Role","Role")))

The result Handout 03COMPSCI 2808

‘Native’ SQL  You can also send ‘native’ SQL direct to the DBMS  Create a string, not interpreted as a query by VS  And send it to the database context with the SqlQuery method  Show the join, and a count(*) Handout 03COMPSCI 2809 string the_name = "Tom"; nativeSQLQuery = String.Format("SELECT COUNT(*) FROM employee WHERE GivenNames='{0}'",the_name); var cnt = db.Database.SqlQuery (nativeSQLQuery); ViewBag.empcnt = "Count=" + cnt.First(); nativeSQLQuery = "SELECT * FROM employee,role WHERE employee.IDnum=role.IDnum;"; var empr = db.Database.SqlQuery (nativeSQLQuery); return View(empr.ToList()); The SqlQuery returns a ‘generic’ class that takes a type parameter (I’m counting here, so int is good) I can just put anything in ViewBag and it’ll be available in the View. Since I was counting I only want the first (and only) item in the collection that was returned Since I’ve typed this as EmpforGrid, I can use it as the Model to pass to my View for the WebGrid

The result  Easily fixed by updating the SQL: nativeSQLQuery = "SELECT *,Year(employee.DateOfBirth) as YearOfBirth FROM employee,role WHERE employee.IDnum=role.IDnum;"; Handout 03COMPSCI Oh, oops! EmpforGrid has a YearOfBirth not a DateofBirth (as in the employee table). It forgave me for leaving it out of the SqlQuery result and put in a ‘convenient’ default Note I’m using the SQL syntax Year() for the conversion, not the C# syntax which is to invoke the.Year method on the DateTime object

What about the rest of the CRUD?!  CRUD  Create, Read, Update, Delete  A CRUD matrix can be a useful specification for the scope of programming tasks  E.g. to describe the ‘life cycle’ of each entity in a system; e.g. a hotel reservation  On some screen (e.g. ‘booking’) it is created (SQL INSERT, not CREATE like making a new table)  There may be a screen to update it (e.g. ‘change booking’) which probably also reads the current value (‘R’ of CRUD, SQL SELECT)  And there will be one or more ways to delete it (e.g. from a cancellation action on the change booking screen or a dedicated cancellation screen, and also once the person has checked in) – then again, you might not actually delete in a SQL sense, but UPDATE it to cancelled or utilised status Handout 03COMPSCI 28011

Where we want to go Handout 03COMPSCI 28012

And when we click an Edit link… Handout 03COMPSCI 28013

The UPDATE  Native SQL version  Given that I have a reference to an object emp of class Employee with updated values: Handout 03COMPSCI using (EmployeesContext db = new EmployeesContext()) { string sql=String.Format( "UPDATE employee SET Surname='{0}',GivenNames='{1}',"+ "DateOfBirth='{2:yyyy-MM-dd}' WHERE IDnum={3}", emp.Surname,emp.GivenNames,emp.DateOfBirth,emp.IDnum); db.Database.ExecuteSqlCommand(sql);... } Here we’re just building the text of a SQL command with the help of String.Format to plug in the parameters from our C# code at the curly braces (note the 3 rd parameter - #2 counting from 0! – is formatted so MySQL recognises the date literal Then we just.ExecuteSqlCommand (as compared doing. SqlQuery) on the database context to tell MySQL to have at it Re-establish the database connection

The UPDATE v2  Entity Framework* version  Now assuming a bit more about emp … not just that it’s an object of class Employee, but that it’s already ‘attached’ to the database context.  As it turns out, this will be a correct assumption once we put this code into the appropriate part of the MVC application * Entity Framework (EF) is an object-relational mapper that enables.NET developers to work with relational data using domain-specific objects – Handout 03COMPSCI using (EmployeesContext db = new EmployeesContext()){ db.Entry(emp).State = EntityState.Modified; db.SaveChanges();... } The 'State' property determines what's done by the SaveChanges method (modified entities are updated)

Putting the update in the MVC context  Making an Edit controller  In HomeController.cs we need a new method to ‘catch’ the invocation of the Edit screen Handout 03COMPSCI public ActionResult Edit(int id) { ViewBag.Message = String.Format( "Your are editing the record for employee ID #{0}.",id); using (EmployeesContext db = new EmployeesContext()) { Employee emp = db.Employees.Find(id); if (emp == null) return HttpNotFound(); return View(emp); }.Find looks up a record from the dbSet based on its primary key (IDnum was set up as such in MySQL and then this was conveyed to the MVC application by the [Key] decorator in the Model If we picked it off the WebGrid table that we ourselves define it really should be found, but good to handle anyway (e.g. user might edit the URL string, or somebody might’ve deleted it since the user last refreshed their browser screen) We’ll set up the invocation such that the IDnum of the selected record is passed to this handler

And we need a second version…  In HomeController.cs we need a second signature for the method  This version catches the Edit screen when it’s being returned to us filled out / updated by the user Handout 03COMPSCI [HttpPost] public ActionResult Edit(Employee emp) { if (ModelState.IsValid) { using (EmployeesContext db = new EmployeesContext()) { db.Entry(emp).State = EntityState.Modified; db.SaveChanges(); } return RedirectToAction("Index"); } return View(emp); } The Edit screen will post back a reference to the whole updated Employee object, emp. If it’s valid (more on that later!) then we save the update to the database If the data was valid, the edit is done so redirect back to the home page; otherwise (there’s some invalid data on the form), present the form to the user again The [HttpPost] decorator signals that this is the one to receive a completed HTML form (the previous one could’ve been annotated as [HttpGet])

Invoking the edit controller  Putting an ActionLink into the WebGrid  To define the column with the Edit link on each employee: grid.Column(header: "Edit", format: (item) => Html.ActionLink("Edit", "Edit", new { id=item.IDnum }))  OK, a bit of cryptic Razor syntax here, but note  We’re creating an ActionLink (labelled “Edit” and that invokes the Edit handler in our controller)  It’s per ‘item’ in the WebGrid (one link for each employee) – ‘item’ is just a magic keyword to indicate the entity on the current row  The => is a ‘lambda expression’ (more on that later… it’s a function as a parameter)  We assign the.IDnum of the current item (i.e. it’s primary key) to ‘id’ – which is the parameter expected by our controller code! Handout 03COMPSCI 28018

Inspecting the HTML  All that Razor boiled down to a hyperlink calling /Home/Edit/2 (the Home controller, looking for the Edit method with a parameter value of 2) Handout 03COMPSCI 28019

Where we’re up to  We’ve seen that we can interact with our DBMS by sending it native SQL or using C#/.NET language-embedded syntax (LINQ and Entity Framework)  And we can add and invoke additional handlers in our controller (e.g. for an Edit/Update function)  FYI: a battery of LINQ examples:  Now…  Work the second labsheet (if you haven’t already)  Get seriously into Assignment 2  Next lecture we’ll look at creating the HTML form to get interactive input from the user for the Edit / Update Handout 03COMPSCI 28020