Chapter 21
Databases

Wrox.com Code Downloads for this Chapter

The wrox.com code downloads for this chapter are found at www.wrox.com/go/beginningvisualc#2015programming on the Download Code tab. The code is in the Chapter 21 download and individually named according to the names throughout the chapter.

The previous chapter introduced LINQ (Language-Integrated Query) and showed how LINQ works with objects and XML. This chapter teaches you how to store your objects in a database and use LINQ to query the data.

Using Databases

A database is a persistent, structured storehouse for data. There are many different kinds of databases, but the most common type you will encounter for storing and querying business data is relational databases such as Microsoft SQL Server and Oracle. Relational databases use the SQL database language (SQL stands for Structured Query Language) to query and manipulate their data. Traditionally, working with such a database required knowing at least some SQL, either embedding SQL statements in your programming language or passing strings containing SQL statements to API calls or methods in a SQL-oriented database class library.

Sounds complicated, doesn't it? Well, the good news is that with Visual C# 2015 you can use a Code First approach to create objects in C#, store them in a database, and use LINQ to query the objects without having to use another language such as SQL.

Installing SQL Server Express

To run the examples shown in this chapter, you must install Microsoft SQL Server Express, the free lightweight version of Microsoft SQL Server. You will use the LocalDB option with SQL Server Express, which enables Visual Studio 2015 to create and open a database file directly without the need to connect to a separate server.

SQL Server Express with LocalDB supports the same SQL syntax as the full Microsoft SQL Server, so it is an appropriate version for beginners to learn on. Download SQL Server express from this link:

http://www.microsoft.com/en-us/server-cloud/products/sql-server-editions/sql-server-express.aspx

Entity Framework

The class library in .NET that supports Code First is the newest version of the Entity Framework. The name comes from a database concept called the entity-relationship model, where an entity is the abstract concept of a data object such as a customer, which is related to other entities such as orders and products (for example, a customer places an order for products) in a relational database.

The Entity Framework maps the C# objects in your program to the entities in a relational database. This is called object-relational mapping. Object-relational mapping is code that maps your classes, objects, and properties in C# to the tables, rows, and columns that make up a relational database. Creating this mapping code by hand is tedious and time-consuming, but the Entity Framework makes it easy!

The Entity Framework is built on top of ADO.NET, the low-level data access library built into .NET. ADO.NET requires some knowledge of SQL, but luckily the Entity Framework also handles this for you and lets you concentrate on your C# code.

Also with the Entity Framework you get LINQ to Entities, the LINQ provider for the Entity Framework that makes querying the database in C# easy. Now you'll get started by creating some objects in a database.

A Code First Database

In the following Try It Out, you create some objects in a database using Code First with the Entity Framework, then query the objects you created using LINQ to Entities.

But Where Is My Database?

But wait, you say. Where is the database you created? You never specified a file name or a folder location—it was all magic! You can see the database in Visual Studio 2015 through the Server Explorer. Go to Tools 1 Connect to Database. The Entity Framework will create a database in the first local SQL Server instance it finds on your computer.

If you never had any databases on your computer previously, Visual C# 2015 creates a local SQL Server instance for you called (localdb)MSSQLLocalDB. To connect to this database type (localdb)MSSQLLocalDB into the Server Name field as shown in Figure 21.8.

Screenshot of Add Connection dialog displaying selected data source, server name, and options to log on to the server and connect to a database.

Figure 21.8

The database containing your data will be called BegVCSharp_21_1_CodeFirstDatabase.BookContext assuming you typed in the example name exactly as shown in the chapter. It will show up in the Select or enter a database name field after taking a moment to connect.

Now you can press OK and the database will appear in the Server Explorer Data Connections window in Visual C# 2015 as shown in Figure 21.9.

Screenshot of the Server Explorer Data Connections window displaying the cascaded Books node with items Code, Title, and Author.

Figure 21.9

From here you can explore the database directly. For example you can right-click on the Books table and choose Show Table Data to see the data you entered as shown in Figure 21.10.

Screenshot of the Server Explorer Data Connections window displaying the cascaded Books node with the Show Table Data option in the right-click menu. On the right is a table listing titles and authors of each code.

Figure 21.10

Navigating Database Relationships

One of the most powerful aspects of the Entity Framework is its capability to automatically create LINQ objects to help you navigate relationships between related tables in the database.

In the following Try It Out, you add two new classes related to the Book class to make a simple bookstore inventory report. The new classes are called Store (to represent each bookstore) and Stock, to represent the inventory of books on hand (in the store on the shelf) and on order from the publisher. A diagram of these new classes and relationships is shown in Figure 21.11.

Diagram of the relationships of class boxes Store, Stock, and Book as connected through items Inventory and Item, respectively.

Figure 21.11

Each store has a name, address, and an Inventory collection consisting of one or more stock objects, one for each different book (title) carried by the store. The relationship between Store and Stock is one-to-many. Each stock record is related to exactly one book. The relationship between Stock and Book is one-to-one. You need the stock record because one store may have three copies of a particular book, but another store will have six copies of the same book.

You'll see how with Code First, all you have to do is create the C# objects and collections, and the Entity Framework will create the database structure for you and let you easily navigate the relationships between your database objects and then query the related objects in the database.

Handling Migrations

Inevitably as you develop your code, you are going to change your mind. You will come up with a better name for one of your properties, or you will realize you need a new class or relationship. If you change the code in a class connected to a database, via the Entity Framework, you will encounter the Invalid Operation Exception shown in Figure 21.14 when you first run the changed program.

Screenshot of an Invalid Operation Exception prompt.

Figure 21.14

Keeping the database up to date with your changed classes is complicated, but again the Entity Framework steps in with a facility to make it relatively easy. As the error message suggests, you need to add the Code First Migrations package to your program.

To do this, go to Tools 1 NuGet Package Manager 1 Package Manager Console. This brings up a command window as shown in Figure 21.15.

To enable automatic migration of your database to your updated class structure, enter this command in the Package Manager Console at the PM> prompt:

Enable-Migrations –EnableAutomaticMigrations
Screenshot of the Package Manager Console window displaying codes for nuget.org packet source.

Figure 21.15

This adds a Migrations class to your project, shown in Figure 21.16.

Screenshot of the Solution Explorer window displaying a tree view of files under BegVCSSharp_21_2_DatabaseRelations. Folder Migrations with configuration file is highlighted.

Figure 21.16

The Entity Framework will compare the timestamp of the database to your program and advise you when the database is out of sync with your classes. To update the database, simply enter this command in the Package Manager Console at the PM> prompt:

Update-Database

Creating and Querying XML from an Existing Database

For the last example you will combine all you have learned about LINQ, databases, and XML.

XML is often used to communicate data between client and server machines or between “tiers” in a multitier application. It is quite common to query for some data in a database and then produce an XML document or fragment from that data to pass to another tier.

In the following Try It Out, you create a query to find some data in the previous example database, use LINQ to Entities to query the data, and then use LINQ to XML classes to convert the data to XML. This is an example of Database First as opposed to Code First programming where you take an existing database and generate C# objects from it.

image What You Learned in this Chapter

Topic Key Concepts
Using Databases A database is a persistent, structured storehouse for data. While there are many different kinds of databases, the most common type used for business data are relational databases.
Entity Framework The Entity Framework is a set of .NET classes for object-relational mapping between C# objects and relational databases.
How to Create Data with Code First By using the Code First classes in the Entity Framework you can create databases directly from C# classes and collections using object-relational mapping.
How to use LINQ with Databases LINQ to Entities enables powerful queries on databases using the same Entity Framework classes to create the data.
How to Navigate Database Relationships The Entity Framework enables creation and navigation of related entities in your database through the use of virtual properties and collections in your C# code.
How to create and query XML from Databases You can construct XML from databases by combining LINQ to Entities, LINQ to Objects, and LINQ to XML in a single query.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset