Upload
guntupallihanu
View
223
Download
0
Embed Size (px)
Citation preview
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 1/20
27/02/200
www.syntrawest.be • erkend door de Vlaamse regering • ISO 9001:2000 gecertificeerd
[te Kortrijk op 26/02/2008]
Data Access in .NET 3.5 withLINQ & ADO Entity FrameworkCLAEYS Kurt (www.devitect.net)
a new developmentenvironment
VS 2008VS 2008
.NET 3.5.NET 3.5LINQLINQ
EntityFramework
EntityFramework
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 2/20
27/02/200
.NET 3.5
• Better integration WCF – WF
• VS2008 aligned to .NET 3.5
• Language enhancements
• LINQ
• Entity Framework (not in VS2008,released together win SQL2008)
• ASP.NET 3.5
Syntra West vzw • Erkend door de Vlaamse Regering • ISO 9001:2000 gecertificeerd • www.syntrawest.be
A problem
Syntra West vzw • Erkend door de Vlaamse Regering • ISO 9001:2000 gecertificeerd • www.syntrawest.be
Objects != Relation DataObjects != XML Data
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 3/20
27/02/200
What Is LINQ?Language Integrated Query
• Built On Top Of .Net 2.0
• Extension Methods
• Anonymous Types
• Standard Query Operators
• Lambda Expressions – Natural evolution of C# 2.0’s anonymous methods
– Expression Trees
• Initializing Compound Values
• Structured values and types
• Implicitly typed local variables
Language Integrated Query
LINQ enabled data sourcesLINQ enabled data sources
LINQTo Objects
ObjectsObjects
LINQ
To XML
<book><title/>
<author/><price/>
</book>
XMLXML
LINQ enabled ADO.NET
LINQ
To DataSets
LINQ
To SQL
LINQ
To Entities
RelationalRelational
Others…VB C#
.NET Language-Integrated Query
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 4/20
27/02/200
How does it work ?
• Standard query operators
• Query expressions
• Extension methods
• Lambda expressions
• Expression trees
• Local variable type inference
The Evolution of C#
C# 1.0
C# 2.0
C# 3.0
Components on a Managed Runtime
Generics
Language Integrated Query
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 5/20
27/02/200
Query Expressions
• Query expressions
• Extension methods
var winners = racers.
Where(r => r.Wins > 3).
OrderByDescending(r => r.Wins).
Select(r => r);
var winners = from r in racers
where r.Wins > 3
orderby r.Wins descending
select r;
Standard Query OperatorsRestrict s.Where(…)
Project s.Select(…), s.SelectMany(…)
Order s.OrderBy(…).ThenBy(…) …
Group s.GroupBy(…)
Quantify s.Any(…), s.All(…)
Partition s.TakeFirst(…), s.SkipFirst(…)
Set s.Distinct(), s.Union(…), s.Intersect(…), s.Except(…)
Singleton s.Element(…), s.ElementAt(…)
Aggregate s.Count(), s.Sum(), s.Min(), s.Max(), s.Average(),s.Aggregate()
Convert s.ToArray(), s.ToList()
Cast s.OfType<T>(), s.Cast<T>
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 6/20
27/02/200
Extension Methods
• Static Methods with this argument
• Method can be invoked with every object of
typeof(this)
public static IEnumerable<T> Where<T>(
this IEnumerable<T> source,
Func<T, bool> predicate)
{
foreach (T item in source)
if (predicate(item))
yield return item;}
Lambda Expressions• Lambda expressions
• Anonymous methods
var winners = racers.Where(
delegate(Racer r)
{return r.Wins > 3;
});
var winners = racers.Where(r => r.Wins > 3);
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 7/20
27/02/200
Local Variable Type Inference
• var keyword
• It's not VARIANT, Object...
• It's the real type!
// var winners = from r in racers
IEnumerable<Racer> winners = from r in racers
where r.Wins > 3
orderby r.Wins descending
select r;
More Language Extensions• Object initalizers
• Anonymous types
new Point { x = 1, y = 2 };
new { c.Name, c.Phone };
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 8/20
27/02/200
The Syntax
from id in source
{ from id in source |
join id in source on expr equals expr [ into id ] |
let id = expr |
where condition |
orderby ordering, ordering, … }
select expr | group expr by key
[ into id query ]
Starts withfrom
Zero or more from , join , let , where , ororderby
Ends withselect or group by
Optional into continuation
Deferred Query ExecutionCustomer[]Customer[] custscusts == SampleData.GetCustomersSampleData.GetCustomers();();
custs
PhoneNameID
var query = from c in custs where c.City == "London" select c.Name;var query = from c in custs where c.City == "London" select c.Name;
var query = custs.Where(c => c.City == "London").Select(c => c.Name);var query = custs.Where(c => c.City == "London").Select(c => c.Name);
Select
c => c.Name
string[] names = query.ToArray();string[] names = query.ToArray();
names
c => c.City == "London"
Where
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 9/20
27/02/200
Architecture
LINQ Query Objects SubmitChanges()
SQL Query Rows SQL or Stored Procs
DLinq
(ADO.NET)
SQLServer
from c in db.Customers
where c.City == "London"
select
new { c.Name, c.Phone }
select Name, Phone
from customers
where city = 'London'
Application
Services:
- Change tracking
- Concurrency control
- Object identity
DLINQ• Language integrated data access
– Maps tables and rows to classes and objects
– Builds on ADO.NET and .NET Transactions
• Mapping – Encoded in attributes
– Relationships map to properties
• Persistence
– Automatic change tracking – Updates through SQL or stored procedures
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 10/20
27/02/200
Data Access In APIs Today
SqlConnection c = new SqlConnection(…);
c.Open();
SqlCommand cmd = new SqlCommand(
@"SELECT c.Name, c.Phone
FROM Customers c
WHERE c.City = @p0"
);
cmd.Parameters.AddWithValue("@po", "London");
DataReader dr = c.Execute(cmd);
while (dr.Read()) {
string name = dr.GetString(0);
string phone = dr.GetString(1);
DateTime date = dr.GetDateTime(2);}
dr.Close();
Queries in quotes
Arguments loosely
bound
Results loosely
typed
Compiler cannothelp catch
mistakes
Data Access with DLINQ
public class Customer
{
public int Id;
public string Name;
public string Phone;
…
}
Table<Customer> customers = db.Customers;
var contacts =from c in customers
where c.City == "London"
select new { c.Name, c.Phone };
Classes describe
data
Tables are
collections
Query is naturalpart of the
language
The compiler helps
you out
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 11/20
27/02/200
XLINQ
• Language integrated query for XML
• Leverages experience with DOM
• Standard Query Operators
• XML Specific Query Operators (Axes)
Programming XML TodayXmlDocument doc = new XmlDocument();
XmlElement contacts = doc.CreateElement("contacts");
foreach (Customer c in customers)
if (c.Country == "USA") {
XmlElement e = doc.CreateElement("contact");
XmlElement name = doc.CreateElement("name");
name.InnerText = c.CompanyName;
e.AppendChild(name);
XmlElement phone = doc.CreateElement("phone");
phone.InnerText = c.Phone;
e.AppendChild(phone);
contacts.AppendChild(e);
}
doc.AppendChild(contacts);
<contacts><contact>
<name>Great Lakes Food</name>
<phone>(503) 555-7123</phone>
</contact>
…
</contacts>
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 12/20
27/02/200
Programming with XLINQ
XElement contacts = new XElement("contacts",
from c in customers
where c.Country == "USA"
select new XElement("contact",
new XElement("name", c.CompanyName),
new XElement("phone", c.Phone)
)
);
That’s LINQ
Syntra West vzw • Erkend door de Vlaamse Regering • ISO 9001:2000 gecertificeerd • www.syntrawest.be
A combination of new language features, andnew fx3.5 classes (with extension methods)
A common query expression syntax
Freedom to implement across different kinds ofdata
It’s TYPED...
The compiler can check your queriesThe compiler can check your results
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 13/20
27/02/200
OR Mapping
Data Access Evolution
Level ofAbstraction
Low-level:databaseschema
Higher-
level:conceptual
schema
QueryLanguage
Query inquotes
Language-
IntegratedQuery(LINQ)
QueryResults
Loosely-typed
(brittle,error-prone)
Strongly-typed
ADO.NET 2.0
ADO.NET
EntityFramework
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 14/20
27/02/200
Introducing the Entity
Framework• API for programming
against entity datamodels
• Layered Architecture
– Object Services(w/LINQ)
– Entity Client
– Existing data
providers
• Query and updatepipelines
• Preserves establishedADO.NET patterns
Introducing the Entity DataModel• Entity Data Model (EDM)
– Vocabulary for describingconceptual schema
– “Shapes the applicationwants to see”
• Entities• Distinct types
• Scalar or complex properties
• Relationships• Describe relations between
entity types
• Explicitly declared: names,cardinality
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 15/20
27/02/200
The Entity Data Model (EDM)
• An Entity-relationship model
• Key Concepts – Entity Type is a structured record with a key
– An Entity is an instance of an Entity Type
– Entities are grouped in Entity-Sets
– Entity types can inherit from other entity types
• The EDM model is effectively “executable”
– Not just to stick to the wall :-)
Relational Data Model
• Almost any businessapplication today hasto speak to a relationaldatabase.
• This involves the usualsuspects of tables with
foreign keys, asmattering of views,and generally a gob ofstored procedures.
Tables
Views
Stored Procedures
Foreign KeyRelationships
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 16/20
27/02/200
The OO model
Objects
Behavior
Properties
Inheritance
Complex Types
• Applications themselves
are written in a
completely different
world.
• The same data that lives
in the relational
database is represented
entirely differently in
the application.
Entity Model ?Logical Data Model
• Tables
• Rows
• Foreign Keys
Entity Data Model
• Entity Sets
• Entities• Relationships
Closer to theapplication problemspace
Better suited for objectoriented programming
Supports Inheritance Supports complex
typesRelationships are more
meaningful to theapplication
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 17/20
27/02/200
EDM Designer in Visual Studio
Logical Model
Store Model
(S-Space)
Conceptual Model
(C - Space)
Object Model
(O – Space)
ADO. Net Provider
e.g. SqlClient
ADO. Net Provider
e.g.EntityClient
Linq
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 18/20
27/02/200
Conceptual ModelTheimagecannot bedisplayed.Your computer may nothaveenough memory to open theimage,or theimagemay havebeen corrupted.Restartyour computer,and then open thefileagain.Ifthe red x stillappears,you may haveto deletetheimageand then insertitagain.
SalesPeople (EntitySet)Theimagecannot bedisplayed.Your computer may nothaveenough memory to open theimage,or theimagemay havebeen corrupted.Restartyour computer,and then open thefileagain.Ifthe red x stillappears,you may haveto deletetheimageand then insertitagain.
SalesOrder (EntitySet)
SalesOrder (Entity Type )
PK ID
OrderDate
Status
AccountNumner
TotalDue
SalesPerson (EntityType )
PK ID
SalesQuota
Bonus
SalesYTD
HireDate
Title
FirstName
LastName
EmailAddess
Phone StoreSalesOrder (EntityType )
Tax
SalesPeron_Order
Moving to the Conceptual Model
C o n c e p t u a l
• Entities, relationships
• Referential constraints
• Shift in future apps
• Target for Entity Framework
SalesPerson
SalesOrder
StoreOrder
SalesPerson
Employee StoreOrder
P h y s i c a l
Contact
• Record formats, file groups
• Indexes, file partitions
• Apps unaware of this level
SalesOrder
L o g i c a l
• Tables, rows, keys
• PK/FK constraints
• Normalization
• Data independence
• Apps of last 20 years
SalesPerson
SalesOrder
Employee Contact
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 19/20
27/02/200
Mapping between the Models
Con. Schema
.csdl File
Create Entity Data
Model
Map between
models
Mapping
.msl File
Generate From
Database
Storage Schema
.ssdl File
Contact
Employee
SalesPerson
SalesOrder
Logical Schema
SalesPeople
SalesOrder
StoreOrder
Conceptual Schema
Demo time
Syntra West vzw • Erkend door de Vlaamse Regering • ISO 9001:2000 gecertificeerd • www.syntrawest.be
8/14/2019 SyntraWest ITClub Seminar Kurt CLAEYS _ Data Access in .NET 3.5 With LINQ & ADO Entity Framework
http://slidepdf.com/reader/full/syntrawest-itclub-seminar-kurt-claeys-data-access-in-net-35-with-linq- 20/20
27/02/200
Syntra West vzw • Erkend door de Vlaamse Regering • ISO 9001:2000 gecertificeerd • www.syntrawest.be
Q&A