144
Chapter 22 (part 2) Databases and LINQ

SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations: a maximum database size

Embed Size (px)

Citation preview

Page 1: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Chapter 22 (part 2)Databases and LINQ

Page 2: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 3: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 4: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

SQL Server Express

SQL Server Express provides many features of Microsoft’s full (fee-based) SQL Server product, but has some limitations: a maximum database size of 10GB.

Versions: http://www.microsoft.com/en-us/sqlserver/editions.aspx

The version of SQL Server Express that’s bundled with Visual Studio Express 2012 for Windows Desktop is called SQL Server Express 2012 LocalDB.

It’s meant for development and testing of apps on your computer.

Page 5: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

LINQ to Entities and the ADO.NET Entity Framework

A logical extension of querying and manipulating data in databases is to perform similar operations on any sources of data, such as arrays, collections (like the Items collection of a ListBox) and files.

Chapter 9 introduced LINQ to Objects and used it to manipulate data stored in arrays.

LINQ to Entities allows you to manipulate data stored in a relational database—in this case, a SQL Server Express database. As with LINQ to Objects, the IDE provides IntelliSense for your LINQ to Entities queries.

Page 6: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

LINQ to Entities and the ADO.NET Entity Framework cont

The ADO.NET Entity Framework (EF) enables apps to interact with data in various forms, including data stored in relational databases.

Visual Studio allows to create a so-called entity data model that represents the database, then use LINQ to Entities to manipulate objects in the entity data model. Though, you’ll manipulate data in a SQL Server Express database, the ADO.NET Entity Framework works with most popular database management systems. Behind the scenes, the ADO.NET Entity Framework generates SQL statements that interact with a database.

LINQ to Entities and the IDE’s tools for working with databases. Later (MIS318), you’ll see other practical database and LINQ to Entities apps, such as a web-based guestbook and a web-based bookstore. Databases are at the heart of most “industrial strength” apps.

Page 7: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

LINQ to SQL vs. LINQ to Entities

In the previous edition of Deitel Csharp How to Program, another technique was used: LINQ to SQL.

Microsoft stopped further development on LINQ to SQL in 2008 in favor of the newer and more powerful LINQ to Entities and the ADO.NET Entity Framework.

Page 8: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 9: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.3 A Books Database

Page 10: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 11: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 12: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 13: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.4. LINQ to Entities and the ADO.NET Entity Framework

Different ways to manipulate the database  http://msdn.microsoft.com/en-us/library/vstudio/

dw70f090%28v=vs.100%29.aspx

When using the ADO.NET Entity Framework, you interact with the database via classes that the IDE generates from the database schema.

One initiates this process by adding a new ADO.NET Entity Data Model to your project.

Page 14: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.4. Classes Generated in the Entity Data Model

For the Authors and Titles tables in the Books database, the IDE creates two classes each in the data model.

The first class represents a row of the table and contains properties for each column in the table. Objects of this class — called row objects —store the data from individual rows of the table. The IDE uses the singular version of a table’s plural name as the row class’s name. For the Books database’s Authors table, the row class’s name is Author, and for the Titles table, it’s Title.

The second class represents the table itself. An object of this class stores a collection of row objects that correspond to all of the rows in the table. The table classes for the Books database are named Authors and Titles.

Page 15: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

What about AuthorISBN table?

AuthorISBN links each author in the Authors table to that author’s books in the Titles table, and

each book in the Titles table to the book’s authors in the Authors table.

Relationships between tables are taken into account in the entity data model’s generated classes. For example, the Author row class contains a navigation property named Titles which you can use to get the Title objects that represent all the books written by that author. The IDE automatically adds the “s” to “Title” to indicate that this property represents a collection of Title objects. Similarly, the Title row class contains a navigation property named Authors, which you can use to get the Author objects that represent a given book’s authors.

Relationships Between Tables in the Entity Data Model

Page 16: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Relationships between tables are taken into account in the entity data model’s generated classes. For example, the Author row class contains a navigation property named Titles which you can use to get the Title objects that represent all the books written by that author.

The IDE automatically adds the “s” to “Title” to indicate that this property represents a collection of Title objects.

Similarly, the Title row class contains a navigation property named Authors, which you can use to get the Author objects that represent a given book’s authors.

Relationships Between Tables in the Entity Data Model

Page 17: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

A DbContext (namespace System.Data.Entity) manages the data flow between the program and the database.

When the IDE generates the entity data model’s row and table classes, it also creates a derived class of DbContext that is specific to the database being manipulated.

For the Books database, this derived class has properties for the Authors and Titles tables. These can be used as data sources for manipulating data in LINQ queries and in

GUIs.

Any changes made to the data managed by the DbContext can be saved back to the database using the DbContext’s SaveChanges method.

DbContext Class

Page 18: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

LINQ to Entities works through the IQueryable<T> interface, which inherits from the interface IEnumerable<T>

When a LINQ to Entities query on an IQueryable<T> object executes against the database, the results are loaded into objects of the corresponding entity data model classes for convenient access in your code.

IQueryable<T> Interface

Page 19: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Extension methods add functionality to an existing class without modifying the class’s source code. In Chapter 9, several LINQ extension methods, including First, Any, Count, Distinct, ToArray and ToList. These methods, which are defined as static methods of class Enumerable (namespace System.Linq), can be applied to any object that implements the IEnumerable<T> interface, such as arrays, collections and the results of LINQ to Objects queries.

Approach here is a Combination of LINQ query syntax and LINQ extension methods to manipulate database contents.

The extension methods used are defined as static methods of class Queryable (namespace System.Linq) and can be applied to any object that implements the IQueryable<T> interface—these include various entity data model objects and the results of LINQ to Entities queries.

Using Extension Methods to Manipulate IQueryable<T> Objects

Page 20: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

connect to a database query it and display the results of the query.

little code - VS provides visual programming tools and wizards that simplify accessing data in apps. These tools establish database connections and create the objects

necessary to view and manipulate the data through Windows Forms GUI controls—a technique known as data binding.

22.5. Querying a Database with LINQ (VISUAL programming)

Page 21: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Reusable component: For the examples 22.5–22.8, reuse one solution that contains several

projects. One will be a reusable class library containing the ADO.NET Entity Data

Model for interacting with the Books database. The other projects will be Windows Forms apps that use the ADO.NET

Entity Data Model in the class library to manipulate the database.

22.5. Querying a Database with LINQ (VISUAL programming)

Page 22: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Query: Retrieve the entire Authors table, ordered by the authors’ last name, then

first name.

Use of data binding to display the data in a DataGridView —a control from namespace System.Windows.Forms that can display data from a data source in tabular format.

Steps:

1. Create the ADO.NET entity data model classes for manipulating the database.

2. Add the entity data model object that represents the Authors table as a data source.

3. Drag the Authors table data source on to the Design view to create a GUI for displaying the table’s data.

4. Add code to the Form’s code-behind file to allow the app to interact with the database.

22.5. Querying a Database with LINQ (VISUAL programming)

Page 23: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.5 Querying a Database with LINQ

All of the controls in this GUI are automatically generated when we drag a data source that represents the Authors table onto the Form in Design view. The BindingNavigator toolbar at the top of the window is a collection of controls that allow you to navigate through the records in the DataGridView that fills the rest of the window. The BindingNavigator controls also allow you to add records, delete records, modify existing records and save your changes to the database. You can add a new record by pressing the Add new (Image) button, then entering the new author’s first and last name. You can delete an existing record by selecting an author (either in the DataGridView or via the controls on the BindingNavigator) and pressing the Delete (Image) button. You can edit an existing record by clicking the first name or last name field for that record and typing the new value. To save your changes to the database, simply click the Save Data (Image) button. Empty values are not allowed in the Authors table of the Books database, so if you attempt to save a record that does not contain a value for both the first name and last name an exception occurs.

Page 24: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

New Project (reusable)

Page 25: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Delete Class1.cs

Page 26: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Add ADO.NET Entity Data Model

Page 27: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Add ADO.NET Entity Data Model cont

Page 28: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 29: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 30: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 31: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

OR

Page 32: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 33: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 34: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 35: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 36: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Choosing the Database Objects to Include in the Model

Choose Your Database Objects and Settings step, you’ll specify the parts of the database that should be used in the ADO.NET Entity Data Model. Select the Tables node as shown in Fig. 22.15, then click Finish.

Page 37: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Singular entity

Avoids naming conflict

* m

any-

to-m

any

Page 38: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Building the Class Library. Select BUILD > Build Solution

Page 39: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Compiles the entity data model classes that were generated by the IDE.

When you build the class library, the IDE generates the classes that you can use to interact with the database.

These include a class for each table you selected from the database and a derived class of DbContext named BooksEntities that enables you to programmatically interact with the database.

Page 40: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Creating ADO.NET Entity Data Model Completed

Steps:

1. Create the ADO.NET entity data model classes for manipulating the database.

2. Add the entity data model object that represents the Authors table as a data source.

3. Drag the Authors table data source on to the Design view to create a GUI for displaying the table’s data.

4. Add code to the Form’s code-behind file to allow the app to interact with the database.

Page 41: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.5.2. Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 1

Create a new Windows Forms app and configure it to be able to use the already created entity data model.

Step 1: Creating the Project

To add a new Windows Forms project to the existing solution:

1. Right click the solution name in Solution Explorer and select Add > New Project... to display the Add New Project dialog.

2. Select Windows Forms Application, name the project DisplayTable and click OK.

3. Change the name of the Form1.cs source file to DisplayAuthorsTable.cs. The IDE updates the Form’s class name to match the source file. Set the Form’s Text property to Display Authors Table.

4. Configure the solution so that this new project will execute when you select DEBUG > Start Debugging (or press F5). To do so, right click the DisplayTable project’s name in the Solution Explorer, then select Set as Startup Project.

Page 42: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 43: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 44: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 45: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.5.2. Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 2 Adding a Reference to the BooksExamples Class Library

To use the entity data model classes for data binding, you must first add a reference to the class library previously created.

This allows the new project to use that class library.

Each project typically contains references to several .NET class libraries (called assemblies) by default—for example, a Windows Forms project contains a reference to the System.Windows.Forms library. When you compile a class library, the IDE creates a .dll file (known as an assembly) containing the library’s components. To add a reference to the class library containing the entity data model’s classes:

1. Right click the DisplayTable project’s References node in the Solution Explorer and select Add Reference....

2. In the left column of the Reference Manager dialog that appears, select Solution to display the other projects in this solution, then in center of the dialog select BooksExamples and click OK. BooksExamples should now appear in the projects References node.

Page 46: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 47: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.5.2. Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 3 Adding References to System.Data.Entity and EntityFramework

Need references to the System.Data.Entity and EntityFramework libraries to use the ADO.NET Entity Framework.

To add a reference to System.Data.Entity, repeat Step 2 for adding a reference to the BooksExamples library, but in the left column of the Reference Manager dialog that appears, select Assemblies then locate System.Data.Entity, ensure that its checkbox is checked and click OK. System.Data.Entity should now appear in the projects References node.

Page 48: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.5.2. Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 3 Adding References to System.Data.Entity and EntityFrameworkcont

The EntityFramework library was added by the IDE to the BooksExamples class library project when the entity data model was created, but the EntityFramework library is also required in each app that will use the entity data model. To add a reference to the EntityFramework library:

1. Right click the solution name in the

Solution Explorer and select Manage

NuGet Packages for Solution...

to display the Manage NuGet Packages

dialog.

http://www.nuget.org/

Page 49: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.5.2. Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 3 Adding References to System.Data.Entity and EntityFrameworkcont

2. In the dialog that appears, click Manage to display the Select Projects dialog, then select the DisplayTable project and click OK.

3. Click Close to close the Manage NuGet Packages dialog. EntityFramework should now appear in the projects References node.References node.

Page 50: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 51: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Each app that uses the entity data model also requires the connection string that tells the Entity Framework how to connect to the database. The connection string is stored in the BooksExamples class library’s App.Config file. In the Solution Explorer, open the BooksExamples class library’s App.Config file then copy lines 7–9, which have the format:

<connectionStrings>

Connection string information appears here

</connectionStrings> <connectionStrings> <add name="BooksEntities" connectionString="metadata=res://*/BooksModel.csdl|res://*/BooksModel.ssdl|res://*/BooksModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Books.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> </connectionStrings>

Next, open the App.Config file in the DisplayTable project and paste the connection string information after the line containing </entityFramework> and before the line containing </configuration>.Save the App.Config file.

22.5.2. Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 4 Adding the Connection String to the Windows Forms App

Page 52: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

<?xml version="1.0" encoding="utf-8"?><configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <connectionStrings> <add name="BooksEntities" connectionString="metadata=res://*/BooksModel.csdl|res://*/BooksModel.ssdl|res://*/BooksModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Books.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> </connectionStrings> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> </entityFramework></configuration>

DisplayTabl App.config

Page 53: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.5.3. Data Bindings Between Controls and the Entity Data Model

Step.1Use the IDE’s drag-and-drop GUI design capabilities to create the GUI for interacting with the Books database.

A small amount of code to enable the autogenerated GUI to interact with the entity data model is required.

Step 1: Adding a Data Source for the Authors Table

1. Select VIEW > Other Windows > Data Sources to display the Data Sources window at the left side of the IDE,

In that window click the Add New Data Source...link to display theData Source Configuration Wizard.

Page 54: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.5.3. Data Bindings Between Controls and the Entity Data ModelStep.1 cont

2. The Entity Data Model classes are used to create objects representing the tables in the database, so we’ll use an Object data source. In the dialog, select Object and click Next >. Expand the tree view  and ensure that Author is checked. An object of this class will be used as the data source.

Page 55: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.5.3. Data Bindings Between Controls and the Entity Data ModelStep.1 cont

3. Click Finish.The Authors table in the database is now a data source from which a data bound GUI control can obtain data. In the Data Sources window, you can see the Author class that you added in the previous step. Properties representing columns of the database’s Authors table should appear below it, as well as a Titles navigation property representing the relationship between the database’s Authors and Titles tables.

Page 56: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.5.3. Data Bindings Between Controls and the Entity Data Model

Step.2 Creating GUI Elements1. Switch to Design view for the DisplayAuthorsTable class.

2. Click the Author node in the Data Sources window—it should change to a drop-down list. Open the drop-down by clicking the down arrow and ensure that the DataGridView option (which is the default) is selected—this is the GUI control that will be used to display and interact with the data.

Page 57: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.5.3. Data Bindings Between Controls and the Entity Data Model

Step.2 Creating GUI Elements

3. Drag the Author node from the Data Sources window onto the Form in Design view. You’ll need to resize the Form to fit the DataGridView.

Page 58: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Behind the Curtain

The IDE creates a DataGridView with column names representing all the properties for an Author, including the Titles navigation property.

The IDE also creates a BindingNavigator that contains Buttons for moving between entries, adding entries, deleting entries and saving changes to the database.

The IDE also generates a BindingSource (authorBindingSource), which handles the transfer of data between the data source and the data-bound controls on the Form.

Nonvisual components such as the BindingSource and the non-visual aspects of the BindingNavigator appear in the component tray—the gray region below the Form in Design view.

The IDE names the BindingNavigator and BindingSource (authorBindingNavigator and authorBindingSource, respectively) based on the data source’s name (Author).

Here default names are used from automatically generated components throughout this chapter to show exactly what the IDE creates.

Page 59: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

GUI

Page 60: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Remove Titles

Page 61: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Remove Titles

Page 62: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.5.3. Data Bindings Between Controls and the Entity Data Model

Step.3 Connecting the Data Source to the authorBindingSource

Page 63: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

DbContext object interacts with the database on the app’s behalf. The BooksEntities class (a derived class of DbContext) was automatically generated by the IDE when you created the entity data model classes to access the Books database (Section 22.5.1).

Page 64: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

You can create the Form’s Load event handler (lines 24–34) by double clicking the Form’s title bar in Design view. In this app, we allow data to move between the DbContext and the database by using LINQ to Entities extension methods to extract data from the BooksEntities’s Authors property (lines 27–30), which corresponds to the Authors table in the database

Page 65: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 66: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Lamda expression

The expression dbcontext.Authorsindicates that we wish to get data from the Authors table.

The OrderBy extension method call.OrderBy( author => author.LastName)

indicates that the rows of the table should be retrieved in ascending order by the authors’ last names.

The argument to OrderBy is a lambda expression that defines a simple, anonymous method. A lambda expression begins with a parameter list — author in this case, is an object of the Author entity data model class. The lambda expression infers the lambda parameter’s type from dbcontext.Authors, which contains Author objects. The parameter list is followed by the => lambda operator (read as “goes to”) and an expression that represents the body of the function. The value produced by the expression—a given author’s last name—is implicitly returned by the lambda expression. You do not specify a return type for the lambda expression—the return type is inferred from the return value.

msdn.microsoft.com/en-us/library/bb397687.aspx

Page 67: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

When there are multiple authors with the same last name to be listed in ascending order by first name as well. The ThenBy extension method call.ThenBy( author => author.FirstName)enables you to order results by an additional column.

This is applied to the Author objects that have already been ordered by last name.

Explanations

Page 68: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

23         // load data from database into DataGridView24         private void DisplayAuthorsTable_Load( object sender, EventArgs e )25         {26            // load Authors table ordered by LastName then FirstName27            dbcontext.Authors                       28               .OrderBy( author => author.LastName )29               .ThenBy( author => author.FirstName )30               .Load();                             31 32            // specify DataSource for authorBindingSource         

Finally, line 30 calls the Load extension method (defined in class DBExtensions from the namespace System.Data.Entity). This method executes the LINQ to Entities query and loads the results into memory. This data is tracked by the BookEntities DbContext in local memory so that any changes made to the data can eventually be saved into the database. Lines 27–30 are equivalent to using the following statement:(from author in dbcontext.Authors orderby author.LastName, author.FirstName select author).Load();

Explanations

Page 69: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

32            // specify DataSource for authorBindingSource33            authorBindingSource.DataSource = dbcontext.Authors.Local;34         } // end method DisplayAuthorsTable_Load

Line 33 sets the authorBindingSource’s DataSource property to the Local property of the dbcontext.Authors object.

In this case, the Local property is an ObservableCollection<Author> that represents the query results that were loaded into memory by lines 27–30.

When a BindingSource’s DataSource property is assigned an ObservableCollection<T> (namespace System.Collections.ObjectModel), the GUI that’s bound to the BindingSource is notified of any changes to the data so the GUI can be updated accordingly. In addition, changes made by the user to the data in the GUI will be tracked so the DbContext can eventually save those changes to the database.

Explanations

Page 70: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

DisabledBy default

authorBindingNavigatorSaveItem_Click Event Handler: Saving Modifications to the Database

If the user modifies the data in the DataGridView, one can save the modifications in the database. To enable the BindingNavigator’s Save Data Button, right click this Button’s icon in the BindingNavigator and select Enabled. Then, double click the icon to create its Click event handler (lines 38–54).

Page 71: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

authorBindingNavigatorSaveItem_Click Event Handler: Saving Modifications to the Database

41            Validate(); // validate the input fields                   42            authorBindingSource.EndEdit(); // complete current edit, if any 43 44            // try to save changes45            try46            {47               dbcontext.SaveChanges(); // write changes to database file 48            } 

Saving the data entered in the DataGridView back to the database is a three-step process.

• First, all controls on the form are validated (line 41) by calling the DisplayTableForm’s inherited Validate method—if any control has an event handler for the Validating event, it executes. Typically handle this event to determine whether a control’s contents are valid.

• Next, line 42 calls EndEdit on the authorBindingSource, which forces it to save any pending changes into the BooksEntities model in memory.

• Finally, line 47 calls SaveChanges on the BooksEntities object (dbcontext) to store any changes into the database.

Using try statement, because the Authors table does not allow empty values for the first name and last name—these rules were configured when database was created. When SaveChanges is called, any changes stored into the Authors table must satisfy the table’s rules. If any of the changes do not, a DBEntityValidationException occurs.

Page 72: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.6 Dynamically Binding Query Results

This app only reads data from the entity data model (disabled the buttons again in the BindingNavigator that enable the user to add and delete records)

Page 73: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 74: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Add New Project DisplayQueryResultrepeat

Page 75: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Configure New Project DisplayQueryResultrepeat

Page 76: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.6. 1 (22.5.2). Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 2 Adding a Reference to the BooksExamples Class Library

To use the entity data model classes for data binding, you must first add a reference to the class library previously created.

This allows the new project to use that class library.

Each project typically contains references to several .NET class libraries (called assemblies) by default—for example, a Windows Forms project contains a reference to the System.Windows.Forms library. When you compile a class library, the IDE creates a .dll file (known as an assembly) containing the library’s components. To add a reference to the class library containing the entity data model’s classes:

1. Right click the DisplayTable project’s References node in the Solution Explorer and select Add Reference....

2. In the left column of the Reference Manager dialog that appears, select Solution to display the other projects in this solution, then in center of the dialog select BooksExamples and click OK. BooksExamples should now appear in the projects References node.

repeat

Page 77: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Add References to BooksExamplesrepeat

Page 78: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.6.1 (22.5.2). Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 3 Adding References to System.Data.Entity and EntityFramework

Need references to the System.Data.Entity and EntityFramework libraries to use the ADO.NET Entity Framework.

To add a reference to System.Data.Entity, repeat Step 2 for adding a reference to the BooksExamples library, but in the left column of the Reference Manager dialog that appears, select Assemblies then locate System.Data.Entity, ensure that its checkbox is checked and click OK. System.Data.Entity should now appear in the projects References node.

repeat

Page 79: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.6.1(22.5.2). Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 3 Adding References to System.Data.Entity and EntityFrameworkcont

The EntityFramework library was added by the IDE to the BooksExamples class library project when the entity data model was created, but the EntityFramework library is also required in each app that will use the entity data model. To add a reference to the EntityFramework library:

1. Right click the solution name in the

Solution Explorer and select Manage

NuGet Packages for Solution...

to display the Manage NuGet Packages

dialog.

http://www.nuget.org/

repeat

Page 80: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.6.1(22.5.2) Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 3 Adding References to System.Data.Entity and EntityFrameworkcont

2. In the dialog that appears, click Manage to display the Select Projects dialog, then select the DisplayTable project and click OK.

3. Click Close to close the Manage NuGet Packages dialog. EntityFramework should now appear in the projects References node.References node.

repeat

Page 81: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

repeat

Page 82: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Each app that uses the entity data model also requires the connection string that tells the Entity Framework how to connect to the database. The connection string is stored in the BooksExamples class library’s App.Config file. In the Solution Explorer, open the BooksExamples class library’s App.Config file then copy lines 7–9, which have the format:

<connectionStrings>

Connection string information appears here

</connectionStrings> <connectionStrings> <add name="BooksEntities" connectionString="metadata=res://*/BooksModel.csdl|res://*/BooksModel.ssdl|res://*/BooksModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Books.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> </connectionStrings>

Next, open the App.Config file in the DisplayTable project and paste the connection string information after the line containing </entityFramework> and before the line containing </configuration>.Save the App.Config file.

22.6.1(22.5.2). Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 4 Adding the Connection String to the Windows Forms App

repeat

Page 83: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

<?xml version="1.0" encoding="utf-8"?><configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> </entityFramework> <connectionStrings> <add name="BooksEntities" connectionString="metadata=res://*/BooksModel.csdl|res://*/BooksModel.ssdl|res://*/BooksModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Books.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> </connectionStrings></configuration>

DisplayQueryResult App.configrepeat

Page 84: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.6.2 (22.5.3.) Data Bindings Between Controls and the Entity Data Model

Step.1Use the IDE’s drag-and-drop GUI design capabilities to create the GUI for interacting with the Books database.

A small amount of code to enable the autogenerated GUI to interact with the entity data model is required.

Step 1: Adding a Data Source for the Authors Table

1. Select VIEW > Other Windows > Data Sources to display the Data Sources window at the left side of the IDE,

In that window click the Add New Data Source...link to display theData Source Configuration Wizard.

repeat

Page 85: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.6.2(22.5.3). Data Bindings Between Controls and the Entity Data Model

Step.1 cont

2. The Entity Data Model classes are used to create objects representing the tables in the database, so we’ll use an Object data source. In the dialog, select Object and click Next >. Expand the tree view  and ensure that Title is checked. An object of this class will be used as the data source.

repeat

Page 86: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.6.2(22.5.3). Data Bindings Between Controls and the Entity Data Model

Step.1 cont

3. Click Finish.The Titles table in the database is now a data source from which a data bound GUI control can obtain data. In the Data Sources window, you can see the Title class that you added in the previous step. Properties representing columns of the database’s Titles table should appear below it, as well as a Authors navigation property representing the relationship between the database’s Titles and Authors tables.

repeat

Page 87: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.6.2(22.5.3). Data Bindings Between Controls and the Entity Data Model

Step.2 Creating GUI Elements1. Switch to Design view for the TitleQueries class.

2. Click the Title node in the Data Sources window—it should change to a drop-down list. Open the drop-down by clicking the down arrow and ensure that the DataGridView option (which is the default) is selected—this is the GUI control that will be used to display and interact with the data.

Page 88: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.6.2(22.5.3). Data Bindings Between Controls and the Entity Data Model

Step.2 Creating GUI Elements

3. Drag the Author node from the Data Sources window onto the Form in Design view. You’ll need to resize the Form to fit the DataGridView.

repeat

Page 89: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.6.2(22.5.3). Remove AuthorsStep.2 Creating GUI Elements

3. Drag the Author node from the Data Sources window onto the Form in Design view. You’ll need to resize the Form to fit the DataGridView.

repeat

Page 90: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

GUI

repeat

Page 91: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.6.1. Creating the Display Query Results GUIStep 3: Adding a ComboBox to the Form

In Design view, add a ComboBox named queriesComboBox below the DataGridView on the Form. Users will select which query to execute from this control. Set the ComboBox’s Dock property to Bottom and the DataGridView’s Dock property to Fill.

Page 92: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.6.1. Creating the Display Query Results GUIStep 3: Adding a ComboBox to the Form

Next, add the names of the queries to the ComboBox. Open the ComboBox’s String Collection Editor by right clicking the ComboBox and selecting Edit Items....

Page 93: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.6.1. Creating the Display Query Results GUIStep 3: Adding a ComboBox to the Form

You can also access the String Collection Editor from the ComboBox’s smart tag menu. A smart tag menu provides you with quick access to common properties you might set for a control (such as the Multiline property of a TextBox), so you can set these properties directly in Design view, rather than in the Properties window.

You can open a control’s smart tag menu by clicking the small arrowhead (Image) that appears in the control’s upper-right corner in Design view when the control is selected. In the String Collection Editor

Page 94: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.6.1. Creating the Display Query Results GUIStep 3: Adding a ComboBox to the Form

Add the following three items to queriesComboBox—one for each of the queries we’ll create:1. All titles2. Titles with 2014 copyright3. Titles ending with "How to Program"

Page 95: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 96: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 97: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 98: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Create the TitleQueries_Load event handler (lines 22–29) by double clicking the title bar in Design view. When the Form loads, it should display the complete list of books from the Titles table, sorted by title.

Line 24 calls the Load extension method on the BookEntities DbContext’s Titles property to load the Titles table’s contents into memory.

Rather than defining the same LINQ query as in lines 40–41, we can programmatically cause the queriesComboBox_SelectedIndexChanged event handler to execute simply by setting the queriesComboBox’s SelectedIndex to 0 (line 28).

Customizing the Form’s Load Event Handler

Page 99: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Next you must write code that executes the appropriate query each time the user chooses a different item from queriesComboBox. Double click queriesComboBox in Design view to generate a queriesComboBox_SelectedIndexChanged event handler (lines 32–63) in the TitleQueries.cs file.

In the event handler, add a switch statement (lines 36–60). Each case in the switch will change the titleBindingSource’s DataSource property to the results of a query that returns the correct set of data.

The data bindings created by the IDE automatically update the titleDataGridView each time we change its DataSource.

The MoveFirst method of the BindingSource (line 62) moves to the first row of the result each time a query executes. The results of the queries in lines 40–41, 46–49 and 54–58 are shown in Fig. 22.21(a), (b) and (c), respectively. Because we do not modify the data in this app, each of the queries is performed on the in-memory representation of the Titles table, which is accessible through dbcontext.Titles.Local.

queriesComboBox_SelectedIndexChanged Event Handler

Page 100: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 101: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

38               case 0: // all titles39                  // use LINQ to order the books by title40                  titleBindingSource.DataSource =                          41                     dbcontext.Titles.Local.OrderBy( book => book.Title1 );42                  break;

Lines 40–41 invoke the OrderBy extension method on dbcontext.Titles.Local to order the Title objects by their Title1 property values.

The IDE renamed the Title column of the database’s Titles table as Title1 in the generated Title entity data model class to avoid a naming conflict with the class’s name.

Local returns an ObservableCollection<T> containing the row objects of the specified table—in this case, Local returns an ObservableCollection<Title>. When you invoke OrderBy on an ObservableCollection<T>, the method returns an IEnumerable<T>. We assign that object to the titleBindingSource’s DataSource property. When the

DataSource property changes, the DataGridView iterates through the contents of the IEnumerable<T> and displays the data

Ordering the Books By Title

Page 102: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

43               case 1: // titles with 2014 copyright44                  // use LINQ to get titles with 201445                  // copyright and sort them by title46                  titleBindingSource.DataSource =                 47                     dbcontext.Titles.Local                       48                        .Where( book => book.Copyright == "2014" )49                        .OrderBy( book => book.Title1 );          50                  break;

Lines 46–49 filter the titles displayed by using the Where extension method with the lambda expression

book => book.Copyright == "2014"

as an argument. This lambda expression takes one Title object (named book) as its parameter and uses it to check whether the given Title’s Copyright property (a string in the database) is equal to 2014.

A lambda expression that’s used with the Where extension method must return a bool value. Only Title objects for which this lambda expression returns true will be selected. We use OrderBy to order the results by the Title1 property so the books are displayed in ascending order by title. The type of the lambda’s book parameter is inferred from dbcontext.Titles.Local, which contains Title objects. As soon as the titleBindingSource’s DataSource property changes, the DataGridView is updated with the query results.

Selecting Books with 2014 Copyright

Page 103: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

51               case 2: // titles ending with "How to Program" 52                  // use LINQ to get titles ending with53                  // "How to Program" and sort them by title54                  titleBindingSource.DataSource =                    55                     dbcontext.Titles.Local                          56                        .Where( book =>                              57                           book.Title1.EndsWith( "How to Program" ) )58                        .OrderBy( book => book.Title1 );             59                  break;

Lines 54–58 filter the titles displayed by using the Where extension method with the lambda expression

book => book.Title1.EndsWith( "How to Program" )

as an argument. This lambda expression takes one Title object (named book) as its parameter and uses it to check whether the given Title’s Title1 property value ends with "How to Program". The expression books.Title1 returns the string stored in that property, then we use the string class’s EndsWith method to perform the test. We order the results by the Title1 property so the books are displayed in ascending order by title.

Selecting Books with Titles That End in “How to Program”

Page 104: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.7 Retrieving Data from Multiple Tables with LINQ

Page 105: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 106: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 107: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Add New Project JoinQueriesrepeat

Page 108: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Configure New Project DisplayQueryResultAgain rename Form.cs to JoiningTableData.cs,

set as Startup project and change Title Joining Tables with LINQ

repeat

Page 109: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.7 (22.5.2). Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 2 Adding a Reference to the BooksExamples Class Library

To use the entity data model classes for data binding, you must first add a reference to the class library previously created.

This allows the new project to use that class library.

Each project typically contains references to several .NET class libraries (called assemblies) by default—for example, a Windows Forms project contains a reference to the System.Windows.Forms library. When you compile a class library, the IDE creates a .dll file (known as an assembly) containing the library’s components. To add a reference to the class library containing the entity data model’s classes:

1. Right click the DisplayTable project’s References node in the Solution Explorer and select Add Reference....

2. In the left column of the Reference Manager dialog that appears, select Solution to display the other projects in this solution, then in center of the dialog select BooksExamples and click OK. BooksExamples should now appear in the projects References node.

repeat

Page 110: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Add References to BooksExamplesrepeat

Page 111: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.7 (22.5.2). Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 3 Adding References to System.Data.Entity and EntityFramework

Need references to the System.Data.Entity and EntityFramework libraries to use the ADO.NET Entity Framework.

To add a reference to System.Data.Entity, repeat Step 2 for adding a reference to the BooksExamples library, but in the left column of the Reference Manager dialog that appears, select Assemblies then locate System.Data.Entity, ensure that its checkbox is checked and click OK. System.Data.Entity should now appear in the projects References node.

repeat

Page 112: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.6.1(22.5.2). Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 3 Adding References to System.Data.Entity and EntityFrameworkcont

The EntityFramework library was added by the IDE to the BooksExamples class library project when the entity data model was created, but the EntityFramework library is also required in each app that will use the entity data model. To add a reference to the EntityFramework library:

1. Right click the solution name in the

Solution Explorer and select Manage

NuGet Packages for Solution...

to display the Manage NuGet Packages

dialog.

http://www.nuget.org/

repeat

Page 113: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.7(22.5.2) Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 3 Adding References to System.Data.Entity and EntityFrameworkcont

2. In the dialog that appears, click Manage to display the Select Projects dialog, then select the DisplayTable project and click OK.

3. Click Close to close the Manage NuGet Packages dialog. EntityFramework should now appear in the projects References node.References node.

repeat

Page 114: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

repeat

Page 115: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Each app that uses the entity data model also requires the connection string that tells the Entity Framework how to connect to the database. The connection string is stored in the BooksExamples class library’s App.Config file. In the Solution Explorer, open the BooksExamples class library’s App.Config file then copy lines 7–9, which have the format:

<connectionStrings>

Connection string information appears here

</connectionStrings> <connectionStrings> <add name="BooksEntities" connectionString="metadata=res://*/BooksModel.csdl|res://*/BooksModel.ssdl|res://*/BooksModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Books.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> </connectionStrings>

Next, open the App.Config file in the JoinQueries project and paste the connection string information after the line containing </entityFramework> and before the line containing </configuration>.Save the App.Config file.

22.6.1(22.5.2). Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 4 Adding the Connection String to the Windows Forms App

repeat

Page 116: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

<?xml version="1.0" encoding="utf-8"?><configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> </entityFramework> <connectionStrings> <add name="BooksEntities" connectionString="metadata=res://*/BooksModel.csdl|res://*/BooksModel.ssdl|res://*/BooksModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Books.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> </connectionStrings></configuration>

JoinQueries App.configrepeat

Page 117: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 118: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 119: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

The code uses the entity data model classes to combine data from the tables in the Books database and display the relationships between the authors and books in three different ways.

the DbContext object (Fig. 22.24, lines 19–20) allows the program to interact with the database.

Page 120: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

The first query (lines 24–27) joins data from two tables and returns a list of author names and the ISBNs representing the books they’ve written, sorted by LastName then FirstName. The query takes advantage of the properties in the entity data model classes that were created based on foreign-key relationships between the database’s tables. These properties enable you to easily combine data from related rows in multiple tables. The first from clause (line 24) gets each author from the Authors table. The second from clause (line 25) uses the generated Titles property of the Author class to get the ISBNs for the current author. The entity data model uses the foreign-key information stored in the database’s AuthorISBN table to get the appropriate ISBNs. The combined result of the two from clauses is a collection of all the authors and the ISBNs of the books they’ve authored. The two from clauses introduce two range variables into the scope of this query—other clauses can access both range variables to combine data from multiple tables. Line 26 orders the results by the author’s LastName, then FirstName. Line 27 creates a new anonymous type that contains the FirstName and LastName of an author from the Authors table with the ISBN of a book in the Titles table written by that author

Page 121: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Anonymous Types new { author.FirstName, author.LastName, book.ISBN };

Anonymous types allow you to create simple classes used to store data without writing a class definition.

An anonymous type declaration (line 27)—known formally as an anonymous object-creation expression—is similar to an object initializer (Section 10.13).

The anonymous type declaration begins with the keyword new followed by a member-initializer list in braces ({}). No class name is specified after the new keyword. The compiler generates a class definition based on the anonymous object-creation expression.

This class contains the properties specified in the member-initializer list— FirstName, LastName and ISBN.

All properties of an anonymous type are public. Anonymous type properties are read-only—you cannot modify a property’s value once the object is created. Each property’s type is inferred from the values assigned to it.

Page 122: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Anonymous Types new { author.FirstName, author.LastName, book.ISBN };

The class definition is generated automatically by the compiler, so you don’t know the class’s type name (hence the term anonymous type).

Thus, you must use implicitly typed local variables to store references to objects of anonymous types (e.g., line 32). Though we are not using it here, the compiler defines a ToString method when creating the anonymous type’s class definition.

The method returns a string in curly braces containing a comma-separated list of PropertyName = value pairs.

The compiler also provides an Equals method, which compares the properties of the anonymous object that calls the method and the anonymous object that it receives as an argument.

Page 123: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

The second query (lines 41–45) gives similar output, but uses the foreign-key relationships to get the title of each book that an author wrote. The first from clause (line 41) gets each book from the Titles table. The second from clause (line 42) uses the generated Authors property of the Title class to get only the authors for the current book. The entity data model uses the foreign-key information stored in the database’s AuthorISBN table to get the appropriate authors. The author objects give us access to the names of the current book’s authors. The select clause (lines 44–45) uses the author and book range variables introduced earlier in the query to get the FirstName and LastName of each author from the Authors table and the title of each book from the Titles table.

Page 124: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Most queries return results with data arranged in a relational-style table of rows and columns. The last query (lines 60–66) returns hierarchical results. Each element in the results contains the name of an Author and a list of Titles that the author wrote. The LINQ query does this by using a nested query in the select clause. The outer query iterates over the authors in the database. The inner query takes a specific author and retrieves all titles that the author wrote. The select clause (lines 62–66) creates an anonymous type with two properties:• The property Name (line 62) combines each author’s name, separating the first and last names by a space.• The property Titles (line 63) receives the result of the nested query, which returns the title of each book written by the current author.In this case, we’re providing names for each property in the new anonymous type. When you create an anonymous type, you can specify the name for each property by using the format name = value.

Page 125: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

The range variable book in the nested query iterates over the current author’s books using in the Titles property. The Title1 property of a given book returns the Title column from that row of the Titles table in the database.The nested foreach statements (lines 71–81) use the properties of the anonymous type created by the query to output the hierarchical results. The outer loop displays the author’s name and the inner loop displays the titles of all the books written by that author.

Page 126: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.8 Creating a Master/Detail View Application

Page 127: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 128: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Add New Project MasterDetail (optional)repeat

Page 129: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Configure New Project DisplayQueryResultAgain rename Form.cs to Detsils.cs, set as

Startup project and change Title Master/Detailrepeat

Page 130: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.8 (22.5.2). Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 2 Adding a Reference to the BooksExamples Class Library

To use the entity data model classes for data binding, you must first add a reference to the class library previously created.

This allows the new project to use that class library.

Each project typically contains references to several .NET class libraries (called assemblies) by default—for example, a Windows Forms project contains a reference to the System.Windows.Forms library. When you compile a class library, the IDE creates a .dll file (known as an assembly) containing the library’s components. To add a reference to the class library containing the entity data model’s classes:

1. Right click the DisplayTable project’s References node in the Solution Explorer and select Add Reference....

2. In the left column of the Reference Manager dialog that appears, select Solution to display the other projects in this solution, then in center of the dialog select BooksExamples and click OK. BooksExamples should now appear in the projects References node.

repeat

Page 131: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.8 (22.5.2). Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 3 Adding References to System.Data.Entity and EntityFramework

Need references to the System.Data.Entity and EntityFramework libraries to use the ADO.NET Entity Framework.

To add a reference to System.Data.Entity, repeat Step 2 for adding a reference to the BooksExamples library, but in the left column of the Reference Manager dialog that appears, select Assemblies then locate System.Data.Entity, ensure that its checkbox is checked and click OK. System.Data.Entity should now appear in the projects References node.

repeat

Page 132: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.6.1(22.5.2). Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 3 Adding References to System.Data.Entity and EntityFrameworkcont

The EntityFramework library was added by the IDE to the BooksExamples class library project when the entity data model was created, but the EntityFramework library is also required in each app that will use the entity data model. To add a reference to the EntityFramework library:

1. Right click the solution name in the

Solution Explorer and select Manage

NuGet Packages for Solution...

to display the Manage NuGet Packages

dialog.

http://www.nuget.org/

repeat

Page 133: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.8(22.5.2) Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 3 Adding References to System.Data.Entity and EntityFrameworkcont

2. In the dialog that appears, click Manage to display the Select Projects dialog, then select the DisplayTable project and click OK.

3. Click Close to close the Manage NuGet Packages dialog. EntityFramework should now appear in the projects References node.References node.

repeat

Page 134: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

repeat

Page 135: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

Each app that uses the entity data model also requires the connection string that tells the Entity Framework how to connect to the database. The connection string is stored in the BooksExamples class library’s App.Config file. In the Solution Explorer, open the BooksExamples class library’s App.Config file then copy lines 7–9, which have the format:

<connectionStrings>

Connection string information appears here

</connectionStrings> <connectionStrings> <add name="BooksEntities" connectionString="metadata=res://*/BooksModel.csdl|res://*/BooksModel.ssdl|res://*/BooksModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Books.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> </connectionStrings>

Next, open the App.Config file in the MasterDetail project and paste the connection string information after the line containing </entityFramework> and before the line containing </configuration>.Save the App.Config file.

22.6.1(22.5.2). Creating a Windows Forms Project and Configuring It to Use the Entity Data Model

STEP 4 Adding the Connection String to the Windows Forms App

repeat

Page 136: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

<?xml version="1.0" encoding="utf-8"?><configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </configSections> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> </entityFramework> <connectionStrings> <add name="BooksEntities" connectionString="metadata=res://*/BooksModel.csdl|res://*/BooksModel.ssdl|res://*/BooksModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Books.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> </connectionStrings></configuration>

MasterDetail App.configrepeat

Page 137: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.8 (22.5.3). Data Bindings Between Controls and the Entity Data Model

Step.1Use the IDE’s drag-and-drop GUI design capabilities to create the GUI for interacting with the Books database.

A small amount of code to enable the autogenerated GUI to interact with the entity data model is required.

Step 1: Adding a Data Source for the Authors Table

1. Select VIEW > Other Windows > Data Sources to display the Data Sources window at the left side of the IDE,

In that window click the Add New Data Source...link to display theData Source Configuration Wizard.

repeat

Page 138: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.8 (22.5.3). Data Bindings Between Controls and the Entity Data Model

Step.1 cont

2. The Entity Data Model classes are used to create objects representing the tables in the database, so we’ll use an Object data source. In the dialog, select Object and click Next >. Expand the tree view  and ensure that Author is checked. An object of this class will be used as the data source.

repeat

Page 139: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

22.8 (22.5.3). Data Bindings Between Controls and the Entity Data Model

Step.1 cont

3. Click Finish.The Authors table in the database is now a data source from which a data bound GUI control can obtain data. In the Data Sources window, you can see the Author class that you added in the previous step. Properties representing columns of the database’s Authors table should appear below it, as well as a Titles navigation property representing the relationship between the database’s Authors and Titles tables.

repeat

Page 140: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 141: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

add

change

By default, the Titles navigation property is implemented in the entity data model classes as a HashSet<Title>. To bind the data to GUI controls properly, you must change this to an ObservableCollection<Title>. To do this, expand the class library project’s BooksModel.edmx node in the Solution Explorer, then expand the BooksModel.tt node and open Author.cs in the editor. Add a using statement for the namespace System.Collections.ObjectModel. Then, in the Author constructor change HashSet to ObservableCollection. Right click the class library project in the Solution Explorer and select Build to recompile the class.

Page 142: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size

1. Switch to Design view for the Details class.

2. Click the Author node in the Data Sources window—it should change to a drop-down list. Open the drop-down by clicking the down arrow and select the Details option—this indicates that we’d like to generate Label–TextBox pairs that represent each column of the Authors table.

3. Drag the Author node from the Data Sources window onto the Form in Design view. This creates the authorBindingSource, the authorBindingNavigator and the Label–TextBox pairs that represent each column in the table. Initially, the controls appear as shown in Fig. 22.29. We rearranged the controls as shown in Fig. 22.28.

Page 143: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size
Page 144: SQL Server Express provides many features of Microsoft’s full (fee- based) SQL Server product, but has some limitations:  a maximum database size