42
Introduction @nalbadia To LINQ & Entity Framework Twitter Hashtags: #NOLtraining #LINQ #EF

Introduction to Linq & Entity Framework

  • Upload
    -

  • View
    4.034

  • Download
    1

Embed Size (px)

DESCRIPTION

محاضرة القيتها في الرياض بعنوان: مقدمة في تقنية LINQ & Entity Framework حيث تسهل عليك هذه التقنية من حفظ بياناتك في قواعد البيانات بطريقة سهلة جدا وفي وقت قياسي مقارنة بالطريقة التقليدية

Citation preview

Page 1: Introduction to Linq & Entity Framework

Introduction

@nalbadia

To LINQ & Entity Framework

Twitter Hashtags: #NOLtraining #LINQ #EF

Page 2: Introduction to Linq & Entity Framework

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

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

ADO.NET 1.0 Architecture

Page 5: Introduction to Linq & Entity Framework

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

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

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

Rows

DataSet

.Net Data ProviderClient

Connection Command

databaseDataAdapter

DataReader

Data Provider Functionality

Page 9: Introduction to Linq & Entity Framework

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

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

Getting data SqlCommand

ExecuteReaderExecuteNonQueryExecuteScalarExecuteXMLReader

SqlDataAdapterDataSet

Page 12: Introduction to Linq & Entity Framework

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

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

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

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

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

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

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

.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

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

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

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

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

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

LINQ operators

Aggregate Conversion Ordering Partitioning SetsAggregateAverageCountMaxMinSum

CastOfTypeToArrayToDictionaryToListToLookupToSequence

OrderByThenByDescendingReverse

SkipSkipWhileTakeTakeWhile

ConcatDistinctExceptIntersectUnion

and many others

Page 26: Introduction to Linq & Entity Framework

Demo

LINQ

Page 27: Introduction to Linq & Entity Framework

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

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

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

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

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

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

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

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

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

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

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

Typical Normalized Tables

Page 39: Introduction to Linq & Entity Framework

Generated Entity Data Model

Page 40: Introduction to Linq & Entity Framework

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

Demo

Entity Framework

Page 42: Introduction to Linq & Entity Framework

42

Q & A