introduction to linq & entity framework

Post on 10-May-2015

4.036 Views

Category:

Technology

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

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

TRANSCRIPT

Introduction

@nalbadia

To LINQ & Entity Framework

Twitter Hashtags: #NOLtraining #LINQ #EF

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

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

ADO.NET 1.0 Architecture

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

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

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

Rows

DataSet

.Net Data ProviderClient

Connection Command

databaseDataAdapter

DataReader

Data Provider Functionality

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

Connecting to SQL

using System.Data.SqlClient;

string sConnectionString = ConfigurationManager.ConnectionStrings["myconnnection"].ConnectionString;

SqlDataAdapter sqlAdp= new SqlDataAdapter(sConnectionString);

sqlAdp.Close();sqlAdp.Dispose();

Getting data SqlCommand

ExecuteReaderExecuteNonQueryExecuteScalarExecuteXMLReader

SqlDataAdapterDataSet

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();

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

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

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

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']

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();

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

.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 };

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)

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

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

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

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

LINQ operators

Aggregate Conversion Ordering Partitioning SetsAggregateAverageCountMaxMinSum

CastOfTypeToArrayToDictionaryToListToLookupToSequence

OrderByThenByDescendingReverse

SkipSkipWhileTakeTakeWhile

ConcatDistinctExceptIntersectUnion

and many others

Demo

LINQ

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

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

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?

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.

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)

Where does EF fit with ADO.NET?

EntityClientConnects to DBExecutes CommandsRetrieves ResultsReshapes Results to match modelReturns tabular data

Data Access

ODBC

OLE DB

ADO.NET(SqlClient)

Level of Abstraction

ADO

RDODataSet

Object RelationalMapping

TypedDataSet

SQL

DAAB

EntityFramework

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 { … }

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

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

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

Typical Normalized Tables

Generated Entity Data Model

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

Demo

Entity Framework

42

Q & A

top related