Vous êtes sur la page 1sur 60

LINQ

Language Integrated Query

LINQ

Unified programming model

Integrated query for objects, databases and XML

The LINQ APIs benefits from

IntelliSense

Full compile-time checking without using string based queries

Query Expression Basics

What is a Query and What Does it Do?

A query is a set of instruction that describes what data to retrieve from a given
data source (or sources) and what shape and organization the returned data should
have.

A query is distinct from the results that it produces

Query Expression Basics

A query may do one of three things

Retrieve a subset of elements to produce a new sequence without modifying the


individual elements.

Retrieve a sequence of elements but transform them to a new type of object

Retrieve a singleton value about the source data

The number of elements that match a certain condition

The element that has the greatest or least value

The first element that matches a condition, or the sum of particular values in a specified
set of elements

What is a Query Expression?

A query expression is a query expressed in query syntax.

Must begin with a from clause and must end with a select or group clause.

Between the first from clause and the last select or group clause, it can contain
one or more of these optional clauses:

where, orderby, join, let and even additional from clauses. You can also use into keyword
to enable the result of a join or group clause to serve as the source for additional query
clauses in the same query expression.

Query Variable

In LINQ, a query variable is any variable that stores a query instead of the
results of a query.

How to Write LINQ Queries in C#

Syntax

Query syntax

Method syntax

Combination of query syntax and method syntax

Query Syntax

Method Syntax

Method Syntax

Lambda expression

Lambda operator (=>)

Read as goes to

Input variable

c => c > 15

Body of the lambda

Same as the query syntax

Mixed Query and Method Syntax

LINQ for In-Memory Collections

Any collection supporting the System.Collections.Generic.IEnumerable


interface or the generic interface IEnumerable<T> is considered a sequence
and can be operated on using the new LINQ standard query operators.

Standard query operators allow programmers to construct queries including


projections that create new types on the fly.

Goes hand-in-hand with type inference, a new feature that allows local variables to
be automatically typed by their initialization expression.

Creating a LINQ Solution

Open Microsoft Visual Studio

Click the File | New | Project menu command.

In the New Project dialog box select the Visual C# Templates project type.

Select the Console Application template.

Provide a name for the new project by entering LINQ Practice in the Name
box.

Click OK.

Exercise I: Querying a Generic List of


Integers

Create a new method with a name NumberQuery that declares a populated


collection of integers (put this method in the Program class)

Values in the collection: 4, 7, 8, 5, 3, 2, 1, 34, 88, 6, 17, 23

Inside the NumberQuery function, write a LINQ query that filters the even
numbers from the original list you have created and assign it to a variable
named evenNumbers.

Inside the NumberQuery function write a console output code that displays
the result.

Querying a Generic List of Integers

Display your result in an ascending order

Display how many even numbers and how many odd numbers does exists in
the list.

Exercise II: Querying Structured Types

Create a Student Class

Add two properties StudentName and City

Override the ToString() function of the class to return the StudentName and
the Address in a tab separated manner

Querying Structured Types

Inside the Program class, add a new method with the following signature
static IEnumerable<Student> CreateStudents()

The method should return a list of students


Name

City

Tadios

Addis Ababa

Ezra

Arba Minch

Martha

Bishoftu

Mahelet

Adama

Sem

Addis Ababa

Zeritu

Bishoftu

Querying Structured Types

Create a method inside the program class with a name ObjectQuery. The
method should have an implementation which query students that live in
Addis Ababa and output the result as a string on the console window.

Call the method from the Main function

Modify your query to display the first student that lives in Bishoftu.

Modify your query to display the first student that lives in Mekele.

Querying Structured Types

Create two classes named Product and Category

The Products class must contain the following properties

Name

Id

CategoryId

The Category class must contain the following properties

Name

Id

Querying Structured Types

Inside the Program class create two methods with the following signatures
static IEnumerable<Category> GetCategories()
static IEnumerable<Product> GetProducts()

The methods should return the following data accordingly


P. Name

Id

Cat. Id

Cat. Name

Id

Orange

Fruits

Banana

Vegetables

Carrots

Beverages

Cabbage

Beer

Milk

Querying Structured Types

Create a method inside the program class with a name JoinQuery. The method
should have an implementation which query products together with their
category and output the result on the console window.

LINQ to SQL

LINQ to SQL is part of the LINQ project

Allows to query and manipulate objects associated with database tables

Eliminates the traditional mismatch between database tables and your


applications domain specific object model, freeing you to work with data as
objects while the framework manages retrieving and updating your objects.

LINQ to SQL

To create an object model of a given database,

Classes must be mapped to database entities.

There are three ways to create object mappings:

Using the provided designer to auto-generate the objects and mappings

Adding attributes to an existing object

Using the command line SQLMetal tool

Creating the application database

Create a database named HSISDB in MS SQL Server Management Studio or


using the Server Explorer window on Visual Studio.

Create a table named Student with the following fields.

StudentId

INT

NOT NULL

FirstName

LastName

NVARCHAR(50)

NOT NULL

City

NVARCHAR(50)

NOT NULL

NVARCHAR(50)

NOT NULL

PRIMARY KEY

Creating the application database

Create a table named Courses with the following fields.

CourseId

INTEGER

NOT NULL

CourseName

NVARCHAR(50)

NOT NULL

CreditHours

INTEGER

PRIMARY KEY

NOT NULL

Create a table named Grade with the following fields.

StudentId

INTEGER

NOT NULL

PRIMARY KEY

CourseId

INTEGER

NOT NULL

PRIMARY KEY

Term

NVARCHAR(50)

NOT NULL

PRIMARY KEY

Grade

NVARCHAR(2)

NOT NULL

Creating the application database

Create a relation between the tables

Add sample data on all tables keeping the relation

Creating the data access

Go to visual studio and create a new console application project

Add an object relational designer for LINQ to SQL

Right click the project and click Add | New Item

In Templates click LINQ to SQL Classes

Provide a name for the new item by entering HSIS

Click OK.

Creating the data access

Expand Data Connections in Server Explorer

Open the SQL Server and find the HSISDB

Open the HSIS.dbml file by double clicking it in Solution Explorer.

Drag and drop all the tables to the HSIS.dbml designer interface.

Creating the data access

Open the program.cs file in Solution Explorer.

Create a method named StudentQuery.

Create an instance of the class HSISDataContext.

Each tables can be accessed as a property for an instance of our designer code,
which is HSISDataContext.

HSISDataContext has inherited from a class named DataCotnext.

The DataContext object used in the Student method is the main conduit through which
objects are retrieved from the database and changes are submitted.

By using the instance of HSISDataContext, query the database to display students


that live in Addis Ababa and display them in the console window.

Modifying Database Data


> Add new data

Create a function called AddData and implement a logic that inserts a new
student in the student table.

FirstName: Biruk, LastName: Asrat, City: Akaki

HINT: Use the InsertOnSubmit or InsertAllOnSubmit methods of the Student table


reference in the context.

Use the SubmitChanges method of the context to apply the update to the
database.

Modifying Database Data


> Updating existing data

Create a function called UpdateData and implement a logic that updates the
city of the student named Ezra to Hawassa.

HINT: Use the SubmitChanges method of the context to apply the update to the
database.

Modifying Database Data


> Delete existing data

Delete a function called DeleteData implement a logic that deletes all


students from Bishoftu.

HINT: Use the DeleteOnSubmit / DeleteAllOnSubmit method of the table reference


in the context to let the context know which data should be deleted.

HINT: Use the SubmitChanges method of the context to apply the delete operation
to the database.

LINQ Exercises using Northwind DB

QUESTION 1:

Write a function named CustomerFilter.

The function should display the customer id, contact name, and city with tab serparation for all customers
whose city is London.

LINQ Exercises using Northwind DB

QUESTION 2:

Write a function named UnitPriceAverage.

The function should display the average of unit price for products with a product name that begins with the
letter A.

HINT: Average, StartsWith

LINQ Exercises using Northwind DB

QUESTION 3:

Write a function named ProductFilter.

The function should display the name and unit price of all products whose product name contains the word
Ch or the unit price is below $5.

HINT: Contains

LINQ Exercises using Northwind DB

QUESTION 4:

Write a function named DiscontinuedProductFilter.

The function should display the name and unit price of all products which are discontinued. Use anonymous
type to select only the product name and unit price.

LINQ Exercises using Northwind DB

QUESTION 5:

Write a function named JanuaryBirthDateFilter.

The function should display the first name and last name of employees whose birthday is in January regardless
of the year they are born in.

LINQ Exercises using Northwind DB

QUESTION 6:

Write a function named ProductSummary.

The function should display the minimum price, the maximum price and the sum of all orders for all products in
the database.

HINT: Min, Max, Sum

LINQ Exercises using Northwind DB

QUESTION 7:

Write a function named CustomersWithOrders.

The function should display the contact name of all customers with at least one
order to their name.

HINT: Any

LINQ Exercises using Northwind DB

QUESTION 8:

Write a function named CustomersWithOrdersFreightUnder50.

The function should display the contact name of all customers whose all orders have
all had freight costs under 50.

HINT: All

Entity Framework

Allows you to create a model by writing code or using boxes and lines in the
EF Designer.

Both of these approaches can be used to target an existing database or create


a new database

Entity Framework

Is an Object Relational Mapper (ORM). It basically generates business objects


and entities according to the database tables and provides the mechanism for:

Performing basic CRUD (Create, Read, Update, Delete) operations

Easily managing 1 to 1, 1 to many and many to many relationships

Ability to have inheritance relationships between entities.

The benefits are

We can have all data access logic written in higher level languages

The conceptual model can be represented in a better way by using relationships


among entities.

The underlying data store can be replaced without much overhead since all data
access logic is present at a higher level.

Entity Framework Architecture Diagram

Entity Framework

EF sits on top of ADO.NET. EF allows you to focus on writing the app rather
than writing a bunch of ADO.NET code.

You are a faster developer using EF.

Your code that is written using ADO.NET can be faster than EF. However, if you
write bad ADO.NET code, it will be slower than EF.

You really have to know what you are doing to make your ADO.NET code
faster than EF. EF performance is quite acceptable for most business
applications. EF is an Object Relational Mapper (ORM) framework similar to
Java's Hibernate.

Entity Framework Workflows

Four development workflows

Question

New Database vs Existing Database?

Boxes or lines vs Writing Code?

Entity Framework Workflows

Entity Framework vs. LINQ to SQL

LINQ to SQL:

Entity Framework:

It only works with SQL Server Database.

It works with various databases

It generates a .dbml to maintain the


relation

It generates an .edmx files

It has support for complex type

It can generate database from model

It allows one-to-on, one-to-many &


many-to-many mappings between
entity classes and relational tables

It allows you to query data using


EntitySQL, Objectcontext, DbContext

It provides a loosely coupled approach.


(Dependency Injection Pattern)

It can be used for rapid application


development with RDBMS

It has no support for complex type.

It cannot generate database from model.

It allows only one to one mapping


between the entity classes and the
relational tables / views.

It allows you to query data using


DataContext

It provides a tightly coupled approach

It can be used to rapid application


development only with SQL Server.

Entity Framework vs. LINQ to SQL

In .NET 3.5, LINQ to SQL had much better support for SQL-Server-specific
functionality than EF. This is mostly not true in .NET 4; theyre fairly similar in
that respect.

The EF let you choose Model First, DB First, or Code First Modeling. LINQ to
SQL, out of the box, really only supports DB First.

Entity Framework Exercise

Create an Existing Database

Open Visual Studio

View -> Server Explorer

Right click on Data Connection -> Add Connection

Select Data Source (If you havent connected to a database from Server
Explorer)

Connect SQL Server, SQL Express or Localdb as your server

Write DatabaseFirst.Blogging as the database name on the connect to a database


option

Select OK and you will be asked if you want to create a new database, select Yes

Entity Framework Exercise

The new database will now appear in Server Explorer, right-click on it and
select New Query

Copy the following SQL into the new query, then right-click on the query and
select Execute

Entity Framework Exercise


CREATE TABLE [dbo].[Blogs] (
[BlogId] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (200) NULL,
[Url] NVARCHAR (200) NULL,
CONSTRAINT [PK_dbo.Blogs] PRIMARY KEY CLUSTERED ([BlogId] ASC)
);
CREATE TABLE [dbo].[Posts] (
[PostId] INT IDENTITY (1, 1) NOT NULL,
[Title] NVARCHAR (200) NULL,
[Content] NTEXT NULL,
[BlogId] INT NOT NULL,
CONSTRAINT [PK_dbo.Posts] PRIMARY KEY CLUSTERED ([PostId] ASC),
CONSTRAINT [FK_dbo.Posts_dbo.Blogs_BlogId] FOREIGN KEY ([BlogId]) REFERENCES [dbo].[Blogs] ([BlogId])
ON DELETE CASCADE
);

Entity Framework Exercise

Creating the Application

Open Visual Studio

File -> New -> Project

Select Windows from the left menu and Console Application

Enter DatabaseFirstPractice as the name

Select OK

Entity Framework Exercise

Reverse Engineer Model

Project -> Add New Item

SelectDatafrom the left menu and thenADO.NET Entity Data Model

EnterBloggingModelas the name and clickOK/Add

This launches theEntity Data Model Wizard

SelectGenerate from Databaseand clickNext

Select the connection to the database you created in the first section,
enterBloggingContextas the name of the connection string and clickNext

Entity Framework Exercise

Entity Framework Version Selection

Depending on the number of versions of Entity Framework installed with


Visual Studio, you might be asked to select the entity framework version.

Choose the latest one and click on Next

Entity Framework 6.x (probably)

Entity Framework Exercise

Click the checkbox next to Tables to import all tables and click Finish

Once the reverse engineer process completes the new model is added to your
project and opened up for you to view in the Entity Framework Designer. An
App.config file has also been added to your project with the connection
details for the database.

Entity Framework Exercise

Reading and Writing Data

In Program.cs class, inside the main function.

Add an implementation to take blog name from user and add it to the database.
After adding it, display all blogs in the database on the console window. The result
might look like this

Entity Framework Exercise

Dealing with Database Changes

Right-click on theDatabaseFirst.Bloggingdatabase in Server Explorer and


selectNew Query

Copy the following SQL into the new query, then right-click on the query and
selectExecute

CREATE TABLE [dbo].[Users]


(
[Username] NVARCHAR(50) NOT NULL PRIMARY KEY,
[DisplayName] NVARCHAR(MAX) NULL
)

Entity Framework Exercise

Right-click on an empty spot of your model in the EF Designer and select


Update Model from Database, this will launch the Update Wizard

On the Add tab of the Update Wizard check the box next to Tables, this
indicates that we want to add any new tables from the schema.

Exercise II

Implement methods that preform the actions specified below.

Create a method named AddBlogs

public void AddBlogs(IEnumerable<Blog> blogs)

The method has a sequence of blogs passed to it. Your code should use the bulk add
method provided by the entity framework data context.

From the console main function, call the method AddBlogs to add the following data to
the database.

Blog Name

URL

Entity Framework Blog

http://blogs.msdn.com/b/adonet/

Physics Blog

http://blog.physicsworld.com/

ADO.NET Blog

http://blogs.msdn.com/b/adonet/

Science Blog

http://scienceblogs.com/channel/environment/?
utm_source=globalChannel&utm_medium=link

IT Blog

http://cee.mit.edu/news/blogs

Exercise II

Create a method named DeleteBlogs

public void DeleteBlogs(IEnumerable<Blog> blogs)

The method has a sequence of blogs passed to it. Your code should use the bulk remove
method provided by the entity framework data context.

From the console main function, call the method DeleteBlogs to remove all blogs with url
value equals http://blogs.msdn.com/b/adonet/.

Vous aimerez peut-être aussi