Connecting a.NET application to a database Jim Warren, COMPSCI 280 S2 2015 Enterprise Software Development.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 15 Introduction to Rails.
Advertisements

Connecting an MVC application to a database Jim Warren, COMPSCI 280 S Enterprise Software Development.
.NET Database Technologies: Open-Source Frameworks.
Oct 31, 2000Database Management -- Fall R. Larson Database Management: Introduction to Terms and Concepts University of California, Berkeley School.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Website Development & Management PHP Odds & Ends Instructor: John Seydel, Ph.D. CIT Fall
Further exploring database operations in MVC Jim Warren, COMPSCI 280 S Enterprise Software Development.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Chapter 12 Database Connectivity with ASP.NET JavaScript, Third Edition.
Access Lecture 1 Database Overview and Creating Tables Create an Employee Table.
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
ORM Technologies and Entity Framework (EF)
Database Constraints. Database constraints are restrictions on the contents of the database or on database operations Database constraints provide a way.
Overview of Database Access in.Net Josh Bowen CIS 764-FS2008.
DAY 21: MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Akhila Kondai October 30, 2013.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Object Oriented Software Development
Introduction to MVC Adding Model Classes NTPCUG Tom Perkins, Ph.D.
 Introduction  What is LINQ  Syntax  How to Query  Example Program.
CSCI 6962: Server-side Design and Programming
Session 5: Working with MySQL iNET Academy Open Source Web Development.
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
ASP.NET Programming with C# and SQL Server First Edition
4-1 INTERNET DATABASE CONNECTOR Colorado Technical University IT420 Tim Peterson.
Database Programming in Java Corresponds with Chapter 32, 33.
Eric Vogel Software Developer A.J. Boggs & Company.
BIT 286: Web Applications Lecture 04 : Thursday, January 15, 2015 ASP.Net MVC - Models.
PHP Programming with MySQL Slide 8-1 CHAPTER 8 Working with Databases and MySQL.
1 MySQL and phpMyAdmin. 2 Navigate to and log on (username: pmadmin)
Chapter 15: Using LINQ to Access Data in C# Programs.
ADO.NET A2 Teacher Up skilling LECTURE 3. What’s to come today? ADO.NET What is ADO.NET? ADO.NET Objects SqlConnection SqlCommand SqlDataReader DataSet.
Web Server Administration Chapter 7 Installing and Testing a Programming Environment.
1 Accelerated Web Development Course JavaScript and Client side programming Day 2 Rich Roth On The Net
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.
ASP.NET MVC applications in C# Jim Warren, COMPSCI 280 S Enterprise Software Development.
Entity Framework Overview. Entity Framework A set of technologies in ADO.NET that support the development of data-oriented software applications A component.
Introduction to ASP.NET MVC Information for this presentation was taken from Pluralsight Building Applications with ASP.NET MVC 4.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Further exploring database operations from C#/.NET Jim Warren, COMPSCI 280 S Enterprise Software Development.
MySQL Connection using ADO.Net Connecting to MySQL from.NET Languages.
Chapter 5 Database Processing. Neil uses software to query a database, but it has about 25 standard queries that don’t give him all he needs. He imports.
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL ADO.Net Basics Ruwan Wijesinghe Trainer.
Database Design and Management CPTG /23/2015Chapter 12 of 38 Functions of a Database Store data Store data School: student records, class schedules,
C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S Enterprise Software Development.
DT228/3 Web Development Databases. Querying a database: Partial info Search engines, on-line catalogues often need to allow user to search a database.
Mr. Justin “JET” Turner CSCI 3000 – Fall 2015 CRN Section A – TR 9:30-10:45 CRN – Section B – TR 5:30-6:45.
Database Access Using JDBC BCIS 3680 Enterprise Programming.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Database Connectivity with ASP.NET. 2 Introduction Web pages commonly used to: –Gather information stored on a Web server database Most server-side scripting.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 2: Introduction to IS2803 Rob Gleasure
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 6: Accessing a database with PHP Rob Gleasure robgleasure.com.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Copyright 2007, Information Builders. Slide 1 iWay Web Services and WebFOCUS Consumption Michael Florkowski Information Builders.
JDBC Java and Databases. SWC – JDBC JDBC – Java DataBase Connectivity An API (i.e. a set of classes and methods), for working with databases in.
SQL pepper. Why SQL File I/O is a great deal of code Optimal file organization and indexing is critical and a great deal of code and theory implementation.
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.
Introduction to Database C# MySQL onnect-C-to-MySQL 1.
MYSQL AND MYSQL WORKBENCH MIS2502 Data Analytics.
Lecture 9:FXML and Useful Java Collections Michael Hsu CSULA.
BIT 286: Web Applications Lecture 04 : Thursday, January 15, 2015 ASP.Net MVC -
Introduction to Database Programming with Python Gary Stewart
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.
ASP.NET Programming with C# and SQL Server First Edition
Introduction to Entity Framework
A very brief introduction
MySQL Connection using ADO.Net
Presentation transcript:

Connecting a.NET application to a database Jim Warren, COMPSCI 280 S Enterprise Software Development

Today’s learning objectives  To be able to program the key components of a C#/.NET application for  Establishing a database connection  Defining a data model for its tables  Querying the database COMPSCI 2802

Getting MySQL and.NET to play together  Principles are the same regardless of the database solution (and largely the same regardless of the application programming language, too)  Get the infrastructure (DBMS and its tools)  Set up a database and get its server running  Establish interoperability of the database and the.NET environment .NET is proprietary to Microsoft, so they’d prefer you ran Microsoft SQL Server (‘Express’ version is free) rather than a competitor such as the free MySQL  Add to your program a ‘connection’  This specifies the running DBMS service, which database (set of tables, views etc.) you want and your ‘login’ as an authorised user on that database  Then you’re free to write a program with logic that interacts with the database COMPSCI 2803

Specifics: setting up a database  Get MySQL running  Ulrich has provided you this, but if you were to set it up at home the steps would be, for instance…  Install XAMPP to get MYSQL, Apache, XAMPP Control Panel and PHPMyAdmin  Then just start Apache* and MySQL in XAMPP Control Panel  Use PHPMyAdmin (or MySQL console) to build a database (‘employee’ for this example) with an employee table, and also to add a user (“jim”) and give that user permissions on the database * Apache only needed for PHPMyAdmin -.NET will use Internet Information Server (IIS) Express to serve the applications Web pages COMPSCI 2804

Specifics: interoperability  Establish interoperability of the technologies  Install MySQL Connector Net on the machine  An ADO.NET driver for MySQL  Install ‘Packages’ on the.NET application  Entity Framework (EF)  Actually not literally needed to work with MySQL, but enhances the ‘level’ at which the application interacts with a relational database (we’ll get back to EF)  MySQL  MySql.Data, MySql.Data.Entities and (for a Web project) MySql.Web  Now your C#/.NET application is ready to talk to a MySQL database through ADO.NET (and extended with EF) COMPSCI 2805

Really ‘raw’ access  Example Handout 02COMPSCI using MySql.Data.MySqlClient;... static void Main(string[] args) { string cs PSCI_280_C_S1_2014"; MySqlConnection conn = null; try { conn = new MySqlConnection(cs); conn.Open(); Console.WriteLine("MySQL version : {0}", conn.ServerVersion); MySqlCommand cmd = new MySqlCommand("select * from employee",conn); MySqlDataReader reader=cmd.ExecuteReader(); reader.Read(); Console.WriteLine(reader.GetString(1)); } catch (MySqlException ex) { Console.WriteLine("Error: {0}", ex.ToString()); } finally { if (conn != null) conn.Close(); }... This was last year’s connection set by Ulrich – a connection needs to specify server, user, password and database Sending text of SQL to the DBMS, then reading one line and printing content of its 2 nd field Closing the database connection when we’re done, managed in try… catch… finally

ADO.NET and Entity Framework  A set of components for accessing data in the.NET framework  Evolved from ‘ActiveX Data Objects’ (ADO) (at least that’s the origin of its name)  Entity Framework (EF) is an open-source object-relational mapping for ADO.NET  Allows us to have a ‘model’ in our application in terms of objects and their properties that corresponds to the relational schema  Really useful so that we have the power of OO programming applied to our database logic  E.g. we get intellisense and compiler errors based on the database- linked objects Handout 02COMPSCI 2807

EF object-relational mapping  A database is mapped to a class  Child class to the general ‘database context’ (DbContext) type  An instance is created when we open a connection  Each table in the database is an object a bit like an array  Each table is a distinct class that inherits from DbSet  A DbSet is a generic type (see us/library/512aeb7t.aspx) that is parameterised with a class for the row instanceshttps://msdn.microsoft.com/en- us/library/512aeb7t.aspx  Each row in the database is an instance of class created to represent the columns of that table  The class has one property per column Handout 02COMPSCI 2808

Specifics: Adding a connection (less raw)  Go into App.config from Solution Explorer (or Web.config for a Web application)  It’s an XML file with project metadata  In the MVC template there’s already a connection defined  For the user accounts that are built into the project by default  We’ll put in another ‘add’ COMPSCI 2809 The connection name will come up in the Model Part of the MySQL packages The MySQL user we defined (and its password! – note you can encrypt part of configuration for security: us/library/ms254494(v=vs.110).aspx

Our Model: Employee.cs COMPSCI using System.Data.Entity; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Console_Connect; { public class EmployeesContext : DbContext { public EmployeesContext() : base("MySqlConnection") { } public DbSet Employees { get; set; } } [Table("employee")] public class Employee { [Key] public int id { get; set; } public string Surname { get; set; } public string GivenNames { get; set; } public DateTime DateOfBirth { get; set; } } First ‘using’ directive is added for referencing the DbContext object; next two are for the ‘key’ and ‘table’ data annotations Use that connection we added to the App.config file Our context’s DbSet ‘Employees’ will be a collection of objects of type Employee The table in MySQL is named ‘employee’ Define properties of this class with names matched to table fields in MySQL ([Key] identifies ‘id’ as the primary key as set in MySQL) Each column modelled as a property (rather than just a field) with default get and set methods namespace matches the application’s Main All public so they’ll be visible to the Main

Some action logic using the model  We can place this in the Main method of a Console application  Or in an event handler or action listener in other application templates COMPSCI using (EmployeesContext db = new EmployeesContext()) { Console.WriteLine(String.Format("Connection string: {0}", db.Database.Connection.ConnectionString)); int j = db.Employees.Count(); Console.WriteLine(String.Format("We have {0} records.", j)); var x2 = db.Database.SqlQuery ("select * from employee"); foreach (Employee emp in x2) { Console.WriteLine(String.Format("Employee: {0}, DoB: {1:d}", emp.Surname,emp.DateOfBirth)); }... Open the connection by making an instance of our specialised child of DbContext; using statement manages closing connection when we leave the statements curly braces db has an Employees class that inherits from DbSet; it has some methods, like count Native SQL query that will return instances of Employee From the model, the compiler knows the names and data types of the properties for a row from the table

Focus on some of language elements  These aren’t restricted to EF or working with databases  Just really handy C# stuff! COMPSCI var x2 = db.Database.SqlQuery ("select * from employee"); foreach (Employee emp in x2) {... ‘Generics’ – take a type as a parameter (marked with angle brackets); let’s us have code that general in terms of the type of object it works with. In this case, we’re saying we expect the method to return an ordered set of whatever is put in the type parameter Implicitly typed local variable (var) – we don’t have to worry on exactly what it’s called… in this case System.Data.Entity.Infrastructure.DbRawSqlQuery (phew!) foreach loop – we get to name the index variable, emp, which is of the type of the elements in the collection x2 (Employee, in this case); you can make a foreach on an array By the way, the system doesn’t actually attempt to run the query until we enumerate it (i.e. until it needs to provide the answer)

And from the model definition  How C# does basic OO COMPSCI public class EmployeesContext : DbContext { public EmployeesContext() : base("MySqlConnection") { }... Colon (:) operator in a class definition says what class to derive a new ‘child’ class from ‘base’ keyword says to access the derived (parent) class; and a public method with the same name as the class is a constructor (runs when we do ‘new’) – so this is saying that a ‘new’ EmployeeContext with no parameters should be implemented as a new DbContext passed the string “MySqlConnection” That’s all we wanted to do, so no code in the curly braces… could’ve added additional stuff to happen after running the parent’s constructor

Query with more specific return value  Let’s say we don’t want all the fields in the table, but just a specific subset  We need a class for the return values  x3 is implicitly typed for the SqlQuery return value, but we still need a parameter for the generic type  Thus we need to add to our model a class definition  We could do something similar if we wanted a subset of fields from a join COMPSCI var x3 = db.Database.SqlQuery ("select Surname,GivenNames from employee"); foreach (EmpName e2 in x3) { Console.WriteLine("Given Names: " + e2.GivenNames + " Surname: " + e2.Surname); }... public class EmpName { public string Surname { get; set; } public string GivenNames { get; set; } }

A query with a ‘lambda’  Built-in methods derived from DbSet* can save us from making an explicit query for many needs  Here the Where method expects as its parameter a function that operates on an instance on the elements of Employees and returns a boolean  We use the ‘lambda’ syntax to specify this (=> operator, can read as ‘such that’)  So this tests each employee record to see if their surname is “Good” (‘a’ is an arbitrary variable name like the iterator variable in a for loop) COMPSCI foreach (var x in db.Employees.Where(a => a.Surname == "Good")) { Console.WriteLine(String.Format("Employee {0}; date of birth: {1:d}", x.GivenNames + " " + x.Surname, x.DateOfBirth)); } * ‘Where’ is actually a method of the ‘Enumberable’ class, but a parent of DbSet implements an ‘interface’ to it

Conclusion  We’ve seen how to work with a database (and MySQL in particular) from C#/.NET  Establishing a connection  Using Entity Framework’s object-relational mapping  Next – we’ll learn about language integrated queries (LINQ) and approaches to updating the database COMPSCI 28016