Introduction to Linq & Entity Framework
-
Upload
- -
Category
Technology
-
view
4.025 -
download
1
description
Transcript of Introduction to Linq & Entity Framework
![Page 1: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/1.jpg)
Introduction
@nalbadia
To LINQ & Entity Framework
Twitter Hashtags: #NOLtraining #LINQ #EF
![Page 2: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/2.jpg)
What is ADO.Net?
The data access classes for the .Net framework
Designed for highly efficient data access Support for XML and disconnected
record sets
![Page 3: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/3.jpg)
Where does ADO sit?V
isual S
tud
io .N
ET
VB C# C++ Jscript …
Common Language Specification
ASP.Net Windows Forms
ADO.Net XML.Net
Base Class Library
Common Language Runtime (CLR)
Windows COM+ Services
![Page 4: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/4.jpg)
ADO.NET 1.0 Architecture
![Page 5: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/5.jpg)
Getting Data From a SQL Database Specific to a particular DBMS
Directly exposes consumer interfaces No more COM/Automation dichotomy
ADO.NET DataProvider Object Model Connection
Establishes connection to DataSource Transaction
Explicit Transaction Control Command
Execute SQL statement DataReader
Forward-only, Read-Only Result Stream Fields accessed through strongly typed, indexed accessors
Data store
DataProvider
Connection
CreateCommand()
ExecuteReader()
DataReader
Command ParametersParametersParameters
![Page 6: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/6.jpg)
Data Sources SQL Data Source (SQLConnection) – used to connect
natively to SQL Server
OLE Data Source (OleDbConnectin) – connect using
ole (object linking and embedding technology)
ODBC Data Source (OdbcDbConnection) – connect
using odbc (Open Database Connectivity )
Oracle DataSource (OracleConnection) – connect
using oracle driver implementation
![Page 7: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/7.jpg)
Client
SQL .NET Data Provider
OLE DB .NET Data Provider
ODBC .NET Data Provider
OLE DB Provider
ODBC Driver
SQL SERVER
Other DB
Other DB
.NET Data Providers
![Page 8: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/8.jpg)
Rows
DataSet
.Net Data ProviderClient
Connection Command
databaseDataAdapter
DataReader
Data Provider Functionality
![Page 9: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/9.jpg)
ADO.Net object modelDataAdapter
Command
DataSet
Errors Collection
Connection Parameters
Data Source
Fill
Update
Sele
ctC
om
mand
Inse
rtC
om
man
d
Upd
ate
Com
mand
Dele
teC
om
man
d
![Page 10: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/10.jpg)
Connecting to SQL
using System.Data.SqlClient;
string sConnectionString = ConfigurationManager.ConnectionStrings["myconnnection"].ConnectionString;
SqlDataAdapter sqlAdp= new SqlDataAdapter(sConnectionString);
sqlAdp.Close();sqlAdp.Dispose();
![Page 11: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/11.jpg)
Getting data SqlCommand
ExecuteReaderExecuteNonQueryExecuteScalarExecuteXMLReader
SqlDataAdapterDataSet
![Page 12: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/12.jpg)
Using the command object
string sSelectQuery = "SELECT * FROM Categories ORDER BY CategoryID";string sConnectionString = ConfigurationManager.ConnectionStrings["myconnnection"].ConnectionString; SqlConnection objConnect = new SqlConnection(sConnectString);SqlCommand objCommand = new SqlCommand(sSelectQuery, objConnect);/*objCommand.CommandTimeout = 15;objCommand.CommandType = CommandType.Text;*/
objConnect.Open();
SqlDataReader drResults;drResults = objCommand.ExecuteReader()
drResults.Close();objConnect.Dispose();
![Page 13: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/13.jpg)
The ProblemProgramming Data is HardWriting queries is difficult
No help from compiler Results are untyped rectangular records
Database Schemas optimized for storage concerns Relational Tables contain flat, homogenous
records Implicit Logic Embedded in Application
Brittle, Hard to maintainLack of common syntax across
relational databases
![Page 14: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/14.jpg)
The OpportunityIncrease Developer Productivity
Rapid Development Strongly typed queries Strongly typed results with Business Logic
Lower TCO Work with an explicit data model
Types, Inheritance, Relationships, Complex Properties,…
Decouple application from storage schemaBetter Portability
Common query language across disparate sources
![Page 15: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/15.jpg)
Introduction to LINQQueries as first-class concept in .NET
languagesBuilds on several language features
Type inference, Delegates, GenericsEnabled by
Lambda expressions Anonymous types Object initialization expressions Extension methods Query expressions
![Page 16: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/16.jpg)
Query without LINQ Objects using loops and conditionsforeach(Customer c in customers) if (c.Region == "UK") ...
Databases using SQLSELECT * FROM Customers WHERE Region='UK'
XML using XPath/XQuery//Customers/Customer[@Region='UK']
![Page 17: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/17.jpg)
ADO without LINQSqlConnection con = new SqlConnection(...);con.Open(); SqlCommand cmd = new SqlCommand( @"SELECT * FROM Customers WHERE c.Region = @Region", con
);cmd.Parameters.AddWithValue("@Region", "UK"); DataReader dr = cmd.ExecuteReader(); while (dr.Read()) { string name = dr.GetString(dr.GetOrdinal("Name")); string phone = dr.GetString(dr.GetOrdinal("Phone")); DateTime date = dr.GetDateTime(3);}dr.Close();con.Close();
![Page 18: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/18.jpg)
Query with LINQ
C#var myCustomers = from c in customers where c.Region == "UK" select c;
VB.NETDim myCustomers = From c In customers _ Where c.Region = "UK" _ Select c
![Page 19: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/19.jpg)
.NET Features// Lambda Expressionsstring[] names = { "Luis", "Mary", "Mike", "Jose" };Display( names, s => s.Length > 3);
// Anonymous Types and object initializationvar emp = new { Name = "Mary", Company = "Microsoft",
Age = 30 };// Extension Methodspublic static class ExtensionMethods { public static void Display<T>(this T[] names,
Func<T, bool> filter) {foreach (T s in names) {
if (filter(s)) Console.WriteLine(s);}
}}// Query Expressionsvar query = from c in Customers
where c.Discount >= 3.0 && c.Discount < 4.0select new { c.Name, Perc = c.Discount / 100.0 };
![Page 20: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/20.jpg)
More LINQ queriesC#
var goodCusts = (from c in db.Customers where c.PostCode.StartsWith("GY") orderby c.Sales descending select c).Skip(10).Take(10);
VB.NET
Dim goodCusts = (From c In db.Customers _ Where c.PostCode.StartsWith("GY") _ Order By c.Sales Descending _ Select c).Skip(1).Take(10)
![Page 21: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/21.jpg)
Advantages Unified data access
Single syntax to learn and remember Strongly typed
Catch errors during compilation IntelliSense
Prompt for syntax and attributes Bindable result sets
![Page 22: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/22.jpg)
Architecture
OthersC# VB.NET
.NET Language Integrated Query (LINQ)
LINQto SQL
LINQto Objects
LINQto XML
LINQto Datasets
LINQto Entities
LINQ data source providers
ADO.NET support for LINQ
![Page 23: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/23.jpg)
LINQ to Objects
C#int[] nums = new int[] {0,4,2,6,3,8,3,1};double average = nums.Take(6).Average();var above = from n in nums where n > average select n;
VB.NETDim nums() As Integer = {0,4,2,6,3,8,3,1}Double average = nums.Take(6).Average()Dim above = From n In nums _ Where n > average _ Select n
![Page 24: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/24.jpg)
LINQ to Objects Query any IEnumerable<T> source
Includes arrays, List<T>, Dictionary... Many useful operators available
Sum, Max, Min, Distinct, Intersect, Union Expose your own data with
IEnumerable<T> or IQueryable<T> Create operators using extension methods
![Page 25: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/25.jpg)
LINQ operators
Aggregate Conversion Ordering Partitioning SetsAggregateAverageCountMaxMinSum
CastOfTypeToArrayToDictionaryToListToLookupToSequence
OrderByThenByDescendingReverse
SkipSkipWhileTakeTakeWhile
ConcatDistinctExceptIntersectUnion
and many others
![Page 26: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/26.jpg)
Demo
LINQ
![Page 27: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/27.jpg)
Object Relational Mapping
Many ORMs out there No clear “winner” = relatively little
adoption of ORM Developers waiting on Microsoft Microsoft shipped two ... hmmm
LINQ to SQL in Visual Studio 2008 ADO.NET Entity Framework in Visual
Studio 2008 SP1
![Page 28: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/28.jpg)
LINQ to SQL Object-relational mapping
Records become strongly-typed objects Data context is the controller mechanism Facilitates update, delete & insert Translates LINQ queries behind the scenes Type, parameter and injection safe
![Page 29: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/29.jpg)
Create data access applications by programming against a conceptual application model instead of programming directly against a relational storage schema.
Decrease the amount of code and maintenance required for data-oriented applications.
What is the Entity Framework?
![Page 30: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/30.jpg)
What is the Entity Framework?
Entity Framework applications provide the following benefits: Applications can work in terms of a more application-centric conceptual
model, including types with inheritance, complex members, and relationships.
Applications are freed from hard-coded dependencies on a particular data engine or storage schema.
Mappings between the conceptual model and the storage-specific schema can change without changing the application code.
Developers can work with a consistent application object model that can be mapped to various storage schemas, possibly implemented in different database management systems.
Multiple conceptual models can be mapped to a single storage schema.
Language-integrated query (LINQ) support provides compile-time syntax validation for queries against a conceptual model.
![Page 31: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/31.jpg)
Where does EF fit with ADO.NET?
Object Services provides• change management• Works with EntityClient to
get and save data• Provides Serialization
(XML and Binary)
![Page 32: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/32.jpg)
Where does EF fit with ADO.NET?
EntityClientConnects to DBExecutes CommandsRetrieves ResultsReshapes Results to match modelReturns tabular data
![Page 33: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/33.jpg)
Data Access
ODBC
OLE DB
ADO.NET(SqlClient)
Level of Abstraction
ADO
RDODataSet
Object RelationalMapping
TypedDataSet
SQL
DAAB
EntityFramework
![Page 34: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/34.jpg)
Entity Framework in a Nutshell
from c in ctx.Customerswhere c.Name.StartsWith(“A”)select c
DB
Entity Framework
CID Name Company
CID Photo StartDate
C3
C2
C1
C3
C2
C1
Model
LINQ Translation
Materialization
Change Tracking
Update Pipeline
class Customer { … }
![Page 35: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/35.jpg)
Entity Framework in a Nutshell
Goal: Simple and seamless data access for the .NET platform Better layering Better re-use of existing knowledge and assets
EDM – Entity Data Model An abstract model for defining entities and relationships Includes schema and mapping
Store Schema Definition (SSDL) Conceptual Schema Definition (CSDL) Mapping Schema between the two (MSL)
Entity Framework An implementation of EDM and an ORM layer on top A framework for using entities over data
![Page 36: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/36.jpg)
Getting Started Database First (VS 2008 and .NET 3.5 SP1)
DB ModelCode
DB ModelCode
DB ModelCode
Design time
Design time
Design time
Design time
Runtime Runtime
Model First (VS 2010 and .NET 4.0)
Code First (Entity Framework Feature CTP3)
why? it already exists, or you want low level control over the database
why? you want separation from code and database in a declarative format
why? primarily focused on code shape, database is an implementation detail
![Page 37: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/37.jpg)
EF Mapping Capabilities Inheritance
Table per Hierarchy Table per Type Table per Concrete
Type Hybrids
Many entities to one table
Stored Procedures Many tables to one
entity
Abstract Entities Associations within
EntitySets Associations across
EntitySets Store-side
discriminators EDM-side
discriminators QueryViews, Defining
Query, CommandText
![Page 38: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/38.jpg)
Typical Normalized Tables
![Page 39: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/39.jpg)
Generated Entity Data Model
![Page 40: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/40.jpg)
Repository
ObjectContext
Database
Business logic, UI, etc.
Testability using Entity Framework
Why: Test business logic, not
database Lightning fast unit tests!
How: swap data access code with in-memory test doubles Choice #1: replace
repository Choice #2: replace context
interface LINQ only
Fake Repository
In-memory data
Real Repository
Fake for context interface
In-memory data
![Page 41: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/41.jpg)
Demo
Entity Framework
![Page 42: Introduction to Linq & Entity Framework](https://reader036.fdocuments.us/reader036/viewer/2022062300/554ebae8b4c905de468b46cc/html5/thumbnails/42.jpg)
42
Q & A