Linq to SQL vs Linq to Entities

  • View
    16

  • Download
    3

Embed Size (px)

DESCRIPTION

Linq to SQL vs Linq to Entities

Text of Linq to SQL vs Linq to Entities

Introducing LINQ

MAHTAB HAIDER

18th April 2014LINQ to SQL vs LINQ to EntitiesTextTextTextTextTextTextTextTextTextTextTextTextDocument NameCONFIDENTIALAgenda 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 NameCONFIDENTIALLINQ: Language INtegrated QueryTextTextTextTextTextTextTextTextTextTextTextTextDocument NameCONFIDENTIALLINQ: 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 NameCONFIDENTIALIntroduction 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 interface. LINQ supports the ADO.NET Entity Framework

- 5 -Document NameCONFIDENTIALLINQArchitecture- 6 -C#.NET Language Integrated Query (LINQ)LINQto SQLLINQto ObjectsLINQto XMLLINQto DatasetsLINQto EntitiesLINQ data source providersADO.NET support for LINQVB.NETOTHERS

Document NameCONFIDENTIALIntroduction 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 NameCONFIDENTIALQuerying without LINQ- 8 -foreach(Customer c in customers) if (c.Region == "USA") ...Objects using loops and conditionsSELECT * FROM Customers WHERE Region='USA'

SELECT from database tables//Customers/Customer[@Region='USA']

XML using XPath/XQueryDocument NameCONFIDENTIALIntroduction 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 NameCONFIDENTIALIntroduction 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 NameCONFIDENTIALLINQ and Generic Types (C#) LINQ query variables are typed as IEnumerable or a derived type such as IQueryable.IEnumerable 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 Variablevar keyword.var customerQuery2 = from cust in customers where cust.City == "London" select cust; foreach(var customer in customerQuery2) { Console.WriteLine(customer.LastName + ", " + customer.FirstName); }

The query specifies what information to retrieve from the data source or sources.

The query expression contains three clauses:

From : Specifies data source Where : applies the filters Select : specifies the type of returned element.- 11 -Document NameCONFIDENTIALLINQ InnovationsQuerying Data with LINQ- 12 -var contacts = from c in customers where c.City == "Hove" select new { c.Name, c.Phone };var contacts = customers .Where(c => c.City == "Hove") .Select(c => new { c.Name, c.Phone });Extension methodsLambda expressionsQuery expressionsObject initializersAnonymous typesLocal variable type inferenceDocument NameCONFIDENTIALTransforming data with LINQTextTextTextTextTextTextTextTextTextTextTextTextDocument NameCONFIDENTIALTransforming data with LINQ Mapping to Another Type or to an Anonymous Object- 14 -IEnumerable users = from emp in employeeswhere emp.ID != 0select new User{Name = emp.First + " " + emp.Last,EmployeeId = emp.ID};var users = from emp in employeeswhere emp.ID != 0select new{Name = emp.First + " " + emp.Last,EmployeeId = emp.ID};Determine type at compile timeSpecifying the Type of AnonymousobjectDetermine type at run timeDocument NameCONFIDENTIALTransforming data with LINQ Merging Multiple Data Sources- 15 -var employeesAndConsul = (from emp in employeeswhere emp.City == "Redmond"select emp.First + " " + emp.Last).Concat(from cn in consultantswhere cn.Location == "Redmond"select cn.Name);Querying from oneData SourceQuerying from anotherData SourceDocument NameCONFIDENTIALTransforming data with LINQ Performing Operations on Results- 16 -var users = from emp in employeesselect new{Employee = string.Format("Employee ({0}), {1}",emp.ID, emp.First + " " + emp.Last),RemainingHoursOff = emp.RemainingVacation + emp.RemainingPersonalTime};Formatting the outputDocument NameCONFIDENTIALTransforming data with LINQ Transforming Results into XML- 17 -var empXml = newXElement("Employees", from emp in employeesselect newXElement("Employee",new XElement("Id", emp.ID),new XElement("Name", emp.First + " " + emp.Last),new XElement("Department", emp.Department)));Document NameCONFIDENTIALTransforming data with LINQ Transforming Results into JSON- 18 -IEnumerable empJson = from emp in employeeswhere emp.Department == "IT Department"select emp;DataContractJsonSerializer ser =new DataContractJsonSerializer(typeof(IEnumerable));MemoryStream ms = new MemoryStream();ser.WriteObject(ms, empJson);string json = Encoding.Default.GetString(ms.ToArray());ms.Close();Response.Write(json);[{"City":"Pittsburgh","Department":"IT Department","First":"Michael","ID":111,"Last":null,{"City":"Redmond","Department":"IT Department","First":"Hank","ID":112,"Last":null}]LINQ QueryFormatting the output in JSONJSON outputDocument NameCONFIDENTIALDefining Entity FrameworkTextTextTextTextTextTextTextTextTextTextTextTextDocument NameCONFIDENTIALDefining Entity Framework- 20 - 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. ADO.NET EvolutionLegacyADO.NET2.0

EntityFramework

LINQtoSQLADO.NETData ServicesAzureTableServicesUnderlying Framework forRIAServicesDocument NameCONFIDENTIALWhat Does It Do?- 21 -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 mappingGenerates mapping/plumbing codeTranslates LINQ queries to database queriesMaterializes objects from data store callsTracks changes, generating updates/insertsDelivers variety of visual modeling tools

Document NameCONFIDENTIALArchitecture of Entity FrameworkTextTextTextTextTextTextTextTextTextTextTextTextDocument NameCONFIDENTIALEntity Framework Architecture- 23 -

Document NameCONFIDENTIALLayered Architecture of Entity Framework- 24 -Core of EFEntity SQLEntity Framework LayerConceptualCSDLMappingMSLLogical StorageSSDL

Entity ClientEntity SQLObject ServicesObject QueryLINQ to EntitiesObject ServicesEntityClientEDMDocument NameCONFIDENTIAL24Rob Vettor25StoreADO.NET Data Provider(SqlClient, OracleClient)CommandConnectionReaderAdapterV3.0Conceptual Data ModelLegacy ADO.NET 2.0 does not go away!ADO.NET Entity Provider (entity client)LINQ to Entities, Entity SQLEntity Framework Programming ModelMappingEntity Framework and ADO.NET Data ServiceDocument NameCONFIDENTIALThe EDM- 26 - Set of objects that describe structure of your business data and map to your underlying data store

Rob Vettor26Contained in Three XML sections stored in [Filename].edmx file:DatabaseSchemaEntityObjectsMappingStorage ModelConceptual ModelDatabaseServicesOOUIDocument NameCONFIDENTIALEntity Framework Recap

- 27 -Document NameCONFIDENTIALEntity Framework Architecture- 28 -

Document NameCONFIDENTIALApproaches for Entity Framework- 29 -

Document NameCONFIDENTIALLINQ and ADO.NET