Sie sind auf Seite 1von 58

LINQ to SQL vs LINQ to Entities

MAHTAB HAIDER
18th April 2014

Agenda

What is LINQ
Transforming Data With LINQ
ADO.NET Entity Framework
LINQ and ADO.NET
LINQ to SQL
LINQ to Entities

Entity Framework vs LINQ to SQL


Summary

-2-

Document Name
CONFIDENTIAL

LINQ: Language INtegrated Query

LINQ: Language-Integrated Query


Language-Integrated Query (LINQ) is a set of features introduced
in .NET framework 3.5 and shipped with Visual Studio 2008
extends powerful query capabilities to the language syntax of C#
and Visual Basic.
LINQ introduces:
standard, easily-learned patterns for querying and updating
data.
the technology to support potentially any kind of data store.
Visual Studio includes LINQprovider assemblies that enable the use
of LINQ with:
.NET Framework collections,
SQL Server databases,
ADO.NET Datasets, and
XML documents.
Enable developers to form set-based queries in their application
code, without having to use a separate query language.
-4-

Document Name
CONFIDENTIAL

Introduction to LINQ:
Innovation introduced in Visual Studio 2008 and .NET Framework
version 3.5 that bridges the gap between the world of objects and
the world of data.

Traditionally we have different query language for each type of


data sources:
SQL databases,
XML documents,
various Web services, and so on.

LINQmakes a query a first-class language construct in C# and VB.


LINQ queries in Visual Basic or C# with
SQL Server databases,
XML documents,
ADO.NET Datasets, and
any collection ofobjects that supports IEnumerable or the generic
IEnumerable<T> interface.
LINQ supports the ADO.NET Entity Framework

-5-

Document Name
CONFIDENTIAL

LINQ

Architecture
C#

OTHERS

VB.NET

.NET Language Integrated Query (LINQ)


LINQ data source providers
ADO.NET support for LINQ
LINQ
to Objects

LINQ
to Datasets

LINQ
to SQL

-6-

LINQ
to Entities

LINQ
to XML

Document Name
CONFIDENTIAL

Introduction to LINQ Queries:

Query is an expression that retrieves data from a data source.


Queries are usually expressed in a specialized query language.
Eg: SQL for relational databases and XQuery for XML.

LINQ simplifies this situation by offering a consistent model for


working with data across various kinds of data sources and formats.

In a LINQ query, we are always working with objects.

We use the samebasic coding patternsto query and transform


data in:
XML documents,
SQL databases,
ADO.NETDatasets,
.NET collections, and
any other format for which a LINQ provider is available.
-7-

Document Name
CONFIDENTIAL

Querying without LINQ

Objects using loops and conditions


foreach(Customer c in customers)
if (c.Region == "USA") ...

SELECT from database tables


SELECT * FROM Customers
WHERE Region='USA'

XML using XPath/XQuery


//Customers/Customer[@Region='USA']

-8-

Document Name
CONFIDENTIAL

Introduction to LINQ Queries:


Three Parts of a Query Operation
All LINQ query operations consist of three distinct actions:
Obtain the data source.
Create the query.
Execute the query.
Complete Query Operation:
Data Source
The Query
Query Execution

-9-

Document Name
CONFIDENTIAL

Introduction to LINQ Queries:


Query Execution
differ in the timing of their execution, depending on whether they
return a singleton value or a sequence of values.
Deferred Execution:
The query variable itself only stores the query commands.
The actual execution of the query is deferred until you iterate over the
query variable in a foreach statement.

Forcing Immediate Execution:


Those methods that return a singleton value (for example,
Average and Sum) execute immediately.
Queries that perform aggregation functions; execute without an
explicit foreach statement because the query itself must use
foreach in order to return a result.
Eg: int evenNumCount = evenNumQuery.Count();

- 10 -

Document Name
CONFIDENTIAL

LINQ and Generic Types (C#)


LINQ query variables are typed as IEnumerable<T> or a derived type
such as IQueryable<T>.
IEnumerable<Customer> customerQuery =
from cust in customers
where cust.City == "London"
select cust;
foreach (Customer customer in customerQuery)
{ Console.WriteLine(customer.LastName + ", " + customer.FirstName);
}

can avoid generic syntax by using the Implicitly Typed Local


Variable
var keyword.
var customerQuery2 =
from cust in customers
where cust.City == "London"
select cust;
foreach(var customer in customerQuery2) {
Console.WriteLine(customer.LastName + ", " + customer.FirstName);
}
- 11 -

Document Name
CONFIDENTIAL

Querying Data with LINQ

LINQ Innovations
var contacts =
from c in customers
where c.City == "Hove"
select new { c.Name, c.Phone };

Query
expressions

Local variable
type
inference
Lambda

Lambda
var contacts =
expressions
customers
.Where(c => c.City == "Hove")
.Select(c => new { c.Name, c.Phone });
Extension
methods

Object
initializers

Anonymous
types
- 12 -

Document Name
CONFIDENTIAL

Transforming data with LINQ

Transforming data with LINQ


Mapping to Another Type or to an Anonymous
Object
IEnumerable<User> users = from emp in employees
where emp.ID != 0
select new User
{
Specifying the
Name = emp.First + " " + emp.Last, Type of Anonymous
EmployeeId = emp.ID
object
Determine type at
};
compile time

Determine type at
run time

var users = from emp in employees


where emp.ID != 0
select new
{
Name = emp.First + " " + emp.Last,
EmployeeId = emp.ID
};
- 14 -

Document Name
CONFIDENTIAL

Transforming data with LINQ


Merging Multiple Data Sources
Querying from one
Data Source

var employeesAndConsul = (from emp in employees


where emp.City == "Redmond"
select emp.First + " " + emp.Last).Concat(
from cn in consultants
where cn.Location == "Redmond"
select cn.Name);
Querying from
another
Data Source

- 15 -

Document Name
CONFIDENTIAL

Transforming data with LINQ


Performing Operations on Results

var users = from emp in employees


select new
{
Employee = string.Format("Employee ({0}), {1}",
emp.ID, emp.First + " " + emp.Last),
RemainingHoursOff = emp.RemainingVacation +
emp.RemainingPersonalTime
};

- 16 -

Formatting the
output

Document Name
CONFIDENTIAL

Transforming data with LINQ


Transforming Results into XML

var empXml = new


XElement("Employees", from emp in employees
select new
XElement("Employee",
new XElement("Id", emp.ID),
new XElement("Name", emp.First + " " + emp.Last),
new XElement("Department", emp.Department)
));

- 17 -

Document Name
CONFIDENTIAL

Transforming data with LINQ


Transforming Results into JSON
LINQ Query
IEnumerable<Employee> empJson = from emp in employees
where emp.Department == "IT Department"
select emp;
Formatting the
output in JSON
DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(IEnumerable<Employee>));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, empJson);
string json = Encoding.Default.GetString(ms.ToArray());
ms.Close();
Response.Write(json);
JSON output
[{"City":"Pittsburgh","Department":"IT Department","First":"Michael","ID":111,
"Last":null,{"City":"Redmond","Department":"IT Department","First":"Hank","ID":112,
"Last":null}]

- 18 -

Document Name
CONFIDENTIAL

Defining Entity Framework

Defining Entity Framework


The ADO.NET Entity Framework is an object relational mapping framework that offers an
abstraction of ADO.NET to get an object model
based on the referential databases.
EF is a data access framework from Microsoft that
helps to build a bridge between the Relation
Database and the Objects in your application.
Legacy
ADO.NET
2.0

ADO.NET Evolution
LINQ
to
SQL

ADO.NET
Entity
Data
Framework
Services

Azure
RIA
Table
Services
Services

Underlying Framework for


- 20 -

Document Name
CONFIDENTIAL

What Does It Do?


It works against conceptual view of your data,
rather than the actual data store itself
Below are the functionalities that Entity Framework provide
automatically:
Generates strongly-typed entity objects that can be
customized beyond 1-1 mapping
Generates mapping/plumbing code
Translates LINQ queries to database queries
Materializes objects from data store calls
Tracks changes, generating updates/inserts
Delivers variety of visual modeling tools

- 21 -

Document Name
CONFIDENTIAL

Architecture of Entity Framework

Entity Framework Architecture

- 23 -

Document Name
CONFIDENTIAL

Layered Architecture of Entity Framework


LINQ to Entities

Object
Services

Object Services
Object Query
Entity SQL

Entity SQL

Entity
Client

Entity Client
Entity Framework Layer
Conceptual

CSDL

EDM

Mapping

MSL

Core of EF

Logical Storage

SSDL

- 24 -

Document Name
CONFIDENTIAL

Entity Framework and ADO.NET Data


Service
Entity Framework
V3.0
LINQ to Entities, Entity SQL
ADO.NET Entity Provider (entity
client)

pi
Map
Mappi
ng
ng

Conceptual Data Model

Programmi
ng
Model

Legacy ADO.NET 2.0 does not go


away!
ADO.NET Data Provider
(SqlClient, OracleClient)

Rob Vettor

Reader

Connection

Adapter

Command

Store
25

Document Name
CONFIDENTIAL

The EDM
Set of objects that describe structure of your
business data and
map to your underlying data store
Contained in Three XML sections stored in [Filename].edmx file:

Database
Schema
Storage Model

Entity
Objects
Mapping

UI

Database

Rob Vettor

Conceptual Model

- 26 -

OO

Services

26

Document Name
CONFIDENTIAL

Entity Framework Recap

- 27 -

Document Name
CONFIDENTIAL

Entity Framework Architecture

- 28 -

Document Name
CONFIDENTIAL

Approaches for Entity Framework

- 29 -

Document Name
CONFIDENTIAL

LINQ and ADO.NET

LINQ to ADO.NET
Enables us to query over any enumerable object in ADO.NET
Three separate LINQ to ADO.NET technologies:
LINQ to DataSet:
provides richer, optimized querying over the DataSet
LINQ to SQL:
enables you to directly query SQL Server database schemas

LINQ to Entities:
allows you to query an Entity Data Model.

- 31 -

Document Name
CONFIDENTIAL

LINQ to SQL

LINQ to SQL
Component of.NET Frameworkversion 3.5 that provides a runtime infrastructure for managing relational data as objects.
Data model of arelational database is mapped to an object
model expressed in programming language.
When the application runs:
LINQ to SQL translates the language-integrated queries in the
object model into SQL
Sends them to the database for execution.
When the database returns the results:
LINQ to SQL translates them back to objects that we can work
within our own programming language.

- 33 -

Document Name
CONFIDENTIAL

LINQ to SQL
Object Relational Designer (O/R Designer) used to create
LINQ to SQL entity classes and associations (relationships) that
are based on objects in a database.
O/R Designer is used to create an object model in an application
that maps to objects in a database.
It also generates a strongly-typed DataContext that is used to
send and receive data between the entity classes and the
database.
O/R Designer also provides functionality to map stored
procedures and functions to DataContext methods for returning
data and populating entity classes.

- 34 -

Document Name
CONFIDENTIAL

LINQ to SQL
Object-relational mapping (ORM)
Records become strongly-typed objects
Includes tracking of changed objects and persistence
Ensures that you will not obtain multiple objects for the
same underlying row in the database

Data context is the controller mechanism


Translates LINQ queries behind the scenes
Facilitates update, delete & insert
Transactionally, with concurrency checks

Type, parameter and injection safe

- 35 -

Document Name
CONFIDENTIAL

LINQ to SQL
Querying Data with LINQ to SQL
Select using LINQ to SQL

// Northwnd inherits from System.Data.Linq.DataContext.


Northwnd nw = new Northwnd(@"northwnd.mdf");
var companyNameQuery =
from cust in nw.Customers
where cust.City == "London"
select cust.CompanyName;
foreach (var customer in companyNameQuery)
{
Console.WriteLine(customer);
}

- 36 -

Document Name
CONFIDENTIAL

LINQ to SQL
Querying Data with LINQ to SQL
Insert with LINQ to SQL
// Northwnd inherits from System.Data.Linq.DataContext.

Northwnd nw = new Northwnd(@"northwnd.mdf");


Customer cust = new Customer();
cust.CompanyName = "SomeCompany";
cust.City = "London";
cust.CustomerID = "98128";
cust.PostalCode = "55555";
cust.Phone = "555-555-5555";
nw.Customers.InsertOnSubmit(cust);
// At this point, the new Customer object is added in the object model.
// In LINQ to SQL, the change is not sent to the database until
// SubmitChanges is called.

nw.SubmitChanges();
- 37 -

Document Name
CONFIDENTIAL

LINQ to SQL
Querying Data with LINQ to SQL
Update with LINQ to SQL

Northwnd nw = new Northwnd(@"northwnd.mdf");


var cityNameQuery =
from cust in nw.Customers
where cust.City.Contains("London")
select cust;
foreach (var customer in cityNameQuery)
{
if (customer.City == "London")
{
customer.City = "London - Metro";
}
}
nw.SubmitChanges();
- 38 -

Document Name
CONFIDENTIAL

LINQ to SQL
Querying Data with LINQ to SQL
Delete with LINQ to SQL

Northwnd nw = new Northwnd(@"northwnd.mdf");


var deleteIndivCust =
from cust in nw.Customers
where cust.CustomerID == "98128"
select cust;
if (deleteIndivCust.Count() > 0)
{
nw.Customers.DeleteOnSubmit(deleteIndivCust.First());
nw.SubmitChanges();
}

- 39 -

Document Name
CONFIDENTIAL

LINQ to SQL
Querying Data with LINQ to SQL
Directly Execute SQL Commands

db.ExecuteCommand("UPDATE Products SET UnitPrice = UnitPrice +


1.00");

- 40 -

Document Name
CONFIDENTIAL

LINQ to SQL
Consisten
cy
Every object will be tracked by LINQ the moment it is
loaded from database.
Conflict checking when SubmitChanges() is called

- 41 -

Document Name
CONFIDENTIAL

LINQ to SQL vs. ADO.NET


Establishing

connection between database & application

ADO.NET
using(SqlConnection conn = new SqlConnection("Connection
String"))
{
conn.Open();
}
LINQ to SQL
NWDataContext db = new NWDataContext("Connection
String");

No need to call any Open() method. Datacontext handles well the


open and close method.

- 42 -

Document Name
CONFIDENTIAL

LINQ to SQL vs. ADO.NET


Getting data from database
ADO.NET
using(SqlConnection conn = new SqlConnection("Connection String")){
using (SqlCommand comm = new SqlCommand("Select * from Customers")) {
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
DataTable dt = new DataTable("New Table");
dt.Load(reader);
} }

LINQ to SQL
using (NorthwindDataContext db = new NorthwindDataContext())
{ IEnumerable<Customer> custs =
from c in db.Customers
select c;
foreach (Customer c in custs) {
Console.WriteLine(c.CompanyName);
} }
- 43 -

Document Name
CONFIDENTIAL

LINQ to SQL vs. ADO.NET


Inserting data into database
ADO.NET
using(SqlConnection conn = new SqlConnection()) {
conn.Open();
SqlCommand comm = new SqlCommand("INSERT INTO...", conn);
comm.ExecuteNonQuery();
}

LINQ to SQL
using (NorthwindDataContext db = new NorthwindDataContext()) {
Customer c = new Customer();
c.CustomerID = "ABCDE";
//.... add all the properties you need to add while inserting
db.Customers.InsertOnSubmit(c);
db.SubmitChanges();
}

- 44 -

Document Name
CONFIDENTIAL

LINQ to SQL vs. ADO.NET


Updating database
ADO.NET
using(SqlConnection conn = new SqlConnection()) {
conn.Open();
SqlCommand comm = new SqlCommand(UPDATE...", conn);
comm.ExecuteNonQuery();
}

LINQ to SQL
using (NorthwindDataContext db = new NorthwindDataContext()) {
Customer cust = (
from c in db.Customers
where c.CustomerID == "ALFKI"
select c).First();

cust.CompanyName = "I do not know?";


db.SubmitChanges();
}

- 45 -

Document Name
CONFIDENTIAL

LINQ to SQL vs. ADO.NET


Deleting database
ADO.NET
using(SqlConnection conn = new SqlConnection()) {
conn.Open();
SqlCommand comm = new SqlCommand(DELETE...", conn);
comm.ExecuteNonQuery();
}

LINQ to SQL
using (NorthwindDataContext db = new NorthwindDataContext()) {
Customer cust = (
from c in db.Customers
where c.CustomerID == "ALFKI"
select c).First();
db.Customers.DeleteOnSubmit(cust);
db.SubmitChanges();
}

- 46 -

Document Name
CONFIDENTIAL

LINQ to SQL vs. ADO.NET


Executing stored proc which returns record(s)
ADO.NET
using(SqlConnection conn = new SqlConnection()) {
conn.Open();
using (SqlCommand comm = new SqlCommand("SalesByCategory", conn))
{
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.AddWithValue("@param1", "value1");
comm.Parameters.AddWithValue("@param2", "value2");
SqlDataReader reader = comm.ExecuteReader();
} }

LINQ to SQL
In LINQ to SQL it becomes method as you drag and drop it to .dbml file,
using (NorthwindDataContext db = new NorthwindDataContext())
{
var outPut = db.SalesByCategory("SeaFood", "1998");
}
- 47 -

Document Name
CONFIDENTIAL

LINQ to SQL
Transaction/Updat
e When update, first check whether new object is
added (by tracking mechanism) if yes, update
statement will be generated otherwise insert will occur
first.
Modification will not hit the database until the
SubmitChanges() method is called
All modifications will be encapsulated into a
transaction.
All operations will be translated into SQL statements
- 48 -

Document Name
CONFIDENTIAL

LINQ to SQL
Transaction/Updat
e

If an exception is throw during the update, all the


changes will be rolled back
One SubmitChanges() is actually one
transaction.(pros and cons?)
Users can also explicitly indicate a new transaction
scope.

- 49 -

Document Name
CONFIDENTIAL

LINQ to Entities

LINQ to Entities
A more advanced ORM solution that allows more
extensive mapping and manipulation between how the
object appears and the underlying data source.
LINQ to Entity provides
Excellent build support; if it isn't mapped 100%, it
won't build.
It works with other databases as well.
It properly separates the structural model from the
conceptual entity model.
It maps many to many relationships properly.

- 51 -

Document Name
CONFIDENTIAL

LINQ to Entities
Querying Data with LINQ to Entities
Model your database using Entity Framework
ORM tool.
- Generates an EDMX file

Query against the model


using (PubsModel.pubsEntities pubs = new PubsModel.pubsEntities())
{
var authQuery = from a in pubs.Authors
where a.state == "CA"
orderby a.LastName
select a;

GridView1.DataSource = authQuery;
GridView1.DataBind();

- 52 -

Document Name
CONFIDENTIAL

Entity Framework vs. LINQ to SQL

EF vs. LINQ-to-SQL
LINQ-to-SQL
Strongly typed LINQ access for RAD against SQL Server
only
Support s only direct Table-Per-Type (1-to-1) mapping
Limited out-of-the box support for complex scenarios

Entity Framework

Designed for larger enterprise applications


Enables complex mapping complex scenarios
Tools and designer more robust
Supports inheritance and many-to-many relationships
Supports provider independence

- 54 -

Document Name
CONFIDENTIAL

EF vs. LINQ-to-SQL
Category

LINQ-to-SQL

Entity Framework

Model

domain model

conceptual data
model

Databases
Supported

SQL server only

SQL server,
OracleDB, DB2 and
many more

Complexity/Learning simple to use


Curve

complex to use

Development Time

rapid development

slower development
but more
capabilities

Mapping

Direct 1-to-1

Custom mapping

Inheritance

hard to apply

simple to apply

- 55 -

Document Name
CONFIDENTIAL

Summary
Q&A

Want more.
Official site
http://msdn.microsoft.com/en-us/library/e80y5yhx.aspx
http://msdn.microsoft.com/en-us/library/vstudio/bb397926.a
spx
http://msdn.microsoft.com/en-us/library/bb399567.aspx
Tutorials
http://weblogs.asp.net/scottgu/archive/tags/LINQ/default.aspx

101 LINQ Samples


http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

- 57 -

Document Name
CONFIDENTIAL

Thank You

Das könnte Ihnen auch gefallen