Linq to SQL vs Linq to Entities

MAHTAB HAIDER 18 th April 2014 LINQ to SQL vs LINQ to Entities


Linq to SQL vs Linq to Entities

Transcript of Linq to SQL vs Linq to Entities

Introducing LINQ


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


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.NETTextTextTextTextTextTextTextTextTextTextTextTextDocument NameCONFIDENTIALLINQ to ADO.NET- 31 - Enables us to query over any enumerable object in ADO.NET Three separate LINQ to ADO.NET technologies:

LINQ to DataSet: provides richer, optimized querying over the DataSetLINQ to SQL: enables you to directly query SQL Server database schemasLINQ to Entities: allows you to query an Entity Data Model. Document NameCONFIDENTIALLINQ to SQLTextTextTextTextTextTextTextTextTextTextTextTextDocument NameCONFIDENTIALLINQ to SQL- 33 - Component of.NET Frameworkversion 3.5 that provides a run-time infrastructure for managing relational data as objects.

Data model of arelational database is mapped to an object model expressed in programming language.

When the application runs: LINQ to SQL translates the language-integrated queries in the object model into SQL Sends them to the database for execution.

When the database returns the results: LINQ to SQL translates them back to objects that we can work within our own programming language.

Document NameCONFIDENTIALLINQ to SQL- 34 - Object Relational Designer (O/R Designer) used to create LINQ to SQL entity classes and associations (relationships) that are based on objects in a database.

O/R Designer is used to create an object model in an application that maps to objects in a database.

It also generates a strongly-typed DataContext that is used to send and receive data between the entity classes and the database.

O/R Designer also provides functionality to map stored procedures and functions to DataContext methods for returning data and populating entity classes.Document NameCONFIDENTIALLINQ to SQL- 35 - Object-relational mapping (ORM) Records become strongly-typed objectsIncludes tracking of changed objects and persistenceEnsures that you will not obtain multiple objects for the same underlying row in the database

Data context is the controller mechanism

Translates LINQ queries behind the scenes

Facilitates update, delete & insert Transactionally, with concurrency checks

Type, parameter and injection safeDocument NameCONFIDENTIALLINQ to SQL- 36 -Querying Data with LINQ to SQLSelect using LINQ to SQL// Northwnd inherits from System.Data.Linq.DataContext. Northwnd nw = new Northwnd(@"northwnd.mdf");

var companyNameQuery = from cust in nw.Customers where cust.City == "London" select cust.CompanyName;

foreach (var customer in companyNameQuery) { Console.WriteLine(customer); } Document NameCONFIDENTIALLINQ to SQL- 37 -Querying Data with LINQ to SQLInsert with LINQ to SQL// Northwnd inherits from System.Data.Linq.DataContext.

Northwnd nw = new Northwnd(@"northwnd.mdf"); Customer cust = new Customer(); cust.CompanyName = "SomeCompany"; cust.City = "London"; cust.CustomerID = "98128"; cust.PostalCode = "55555"; cust.Phone = "555-555-5555"; nw.Customers.InsertOnSubmit(cust);

// At this point, the new Customer object is added in the object model. // In LINQ to SQL, the change is not sent to the database until // SubmitChanges is called.

nw.SubmitChanges();Document NameCONFIDENTIALLINQ to SQL- 38 -Querying Data with LINQ to SQLUpdate with LINQ to SQLNorthwnd nw = new Northwnd(@"northwnd.mdf"); var cityNameQuery = from cust in nw.Customers where cust.City.Contains("London") select cust;

foreach (var customer in cityNameQuery) { if (customer.City == "London") { customer.City = "London - Metro"; } } nw.SubmitChanges();Document NameCONFIDENTIALLINQ to SQL- 39 -Querying Data with LINQ to SQLDelete with LINQ to SQLNorthwnd nw = new Northwnd(@"northwnd.mdf"); var deleteIndivCust = from cust in nw.Customers where cust.CustomerID == "98128" select cust; if (deleteIndivCust.Count() > 0) { nw.Customers.DeleteOnSubmit(deleteIndivCust.First()); nw.SubmitChanges(); }Document NameCONFIDENTIALLINQ to SQL- 40 -Querying Data with LINQ to SQLDirectly Execute SQL Commandsdb.ExecuteCommand("UPDATE Products SET UnitPrice = UnitPrice + 1.00");Document NameCONFIDENTIALLINQ to SQL- 41 -Every object will be tracked by LINQ the moment it is loaded from database.

Conflict checking when SubmitChanges() is calledConsistencyDocument NameCONFIDENTIALLINQ to SQL vs. ADO.NET

- 42 - ADO.NETusing(SqlConnection conn = new SqlConnection("Connection String")){ conn.Open();}LINQ to SQL NWDataContext db = new NWDataContext("Connection String"); No need to call any Open() method. Datacontext handles well the open and close method.Establishing connection between database & applicationDocument NameCONFIDENTIALLINQ to SQL vs. ADO.NET

- 43 - ADO.NETusing(SqlConnection conn = new SqlConnection("Connection String")){ using (SqlCommand comm = new SqlCommand("Select * from Customers")) { conn.Open(); SqlDataReader reader = comm.ExecuteReader(); DataTable dt = new DataTable("New Table"); dt.Load(reader); } }LINQ to SQLusing (NorthwindDataContext db = new NorthwindDataContext()){ IEnumerable custs = from c in db.Customers select c; foreach (Customer c in custs) { Console.WriteLine(c.CompanyName); } }Getting data from databaseDocument NameCONFIDENTIALLINQ to SQL vs. ADO.NET

- 44 - ADO.NETusing(SqlConnection conn = new SqlConnection()) { conn.Open(); SqlCommand comm = new SqlCommand("INSERT INTO...", conn); comm.ExecuteNonQuery();}LINQ to SQLusing (NorthwindDataContext db = new NorthwindDataContext()) { Customer c = new Customer(); c.CustomerID = "ABCDE"; //.... add all the properties you need to add while inserting db.Customers.InsertOnSubmit(c);db.SubmitChanges(); }Inserting data into databaseDocument NameCONFIDENTIALLINQ to SQL vs. ADO.NET

- 45 - ADO.NETusing(SqlConnection conn = new SqlConnection()) { conn.Open(); SqlCommand comm = new SqlCommand(UPDATE...", conn); comm.ExecuteNonQuery();}LINQ to SQLusing (NorthwindDataContext db = new NorthwindDataContext()) {Customer cust = (from c in db.Customers where c.CustomerID == "ALFKI" select c).First(); cust.CompanyName = "I do not know?"; db.SubmitChanges(); }Updating databaseDocument NameCONFIDENTIALLINQ to SQL vs. ADO.NET

- 46 - ADO.NETusing(SqlConnection conn = new SqlConnection()) { conn.Open(); SqlCommand comm = new SqlCommand(DELETE...", conn); comm.ExecuteNonQuery();}LINQ to SQLusing (NorthwindDataContext db = new NorthwindDataContext()) { Customer cust = (from c in db.Customers where c.CustomerID == "ALFKI" select c).First();db.Customers.DeleteOnSubmit(cust);db.SubmitChanges(); }Deleting databaseDocument NameCONFIDENTIALLINQ to SQL vs. ADO.NET

- 47 - ADO.NET using(SqlConnection conn = new SqlConnection()) { conn.Open(); using (SqlCommand comm = new SqlCommand("SalesByCategory", conn)) { comm.CommandType = CommandType.StoredProcedure; comm.Parameters.AddWithValue("@param1", "value1"); comm.Parameters.AddWithValue("@param2", "value2"); SqlDataReader reader = comm.ExecuteReader(); } }LINQ to SQLIn LINQ to SQL it becomes method as you drag and drop it to .dbml file,using (NorthwindDataContext db = new NorthwindDataContext()){ var outPut = db.SalesByCategory("SeaFood", "1998"); }Executing stored proc which returns record(s)Document NameCONFIDENTIALLINQ to SQL- 48 - When update, first check whether new object is added (by tracking mechanism) if yes, update statement will be generated otherwise insert will occur first.

Modification will not hit the database until the SubmitChanges() method is called

All modifications will be encapsulated into a transaction.

All operations will be translated into SQL statementsTransaction/UpdateDocument NameCONFIDENTIALLINQ to SQL- 49 - If an exception is throw during the update, all the changes will be rolled back

One SubmitChanges() is actually one transaction.(pros and cons?)

Users can also explicitly indicate a new transaction scope.Transaction/UpdateDocument NameCONFIDENTIALLINQ to EntitiesTextTextTextTextTextTextTextTextTextTextTextTextDocument NameCONFIDENTIALLINQ to Entities- 51 - A more advanced ORM solution that allows more extensive mapping and manipulation between how the object appears and the underlying data source.

LINQ to Entity provides Excellent build support; if it isn't mapped 100%, it won't build. It works with other databases as well. It properly separates the structural model from the conceptual entity model. It maps many to many relationships properly.

Document NameCONFIDENTIALLINQ to Entities- 52 -- 52 -Querying Data with LINQ to Entities Model your database using Entity Framework ORM tool.- Generates an EDMX file

Query against the model

using (PubsModel.pubsEntities pubs = new PubsModel.pubsEntities()){var authQuery = from a in pubs.Authorswhere a.state == "CA"orderby a.LastNameselect a;

GridView1.DataSource = authQuery;GridView1.DataBind();}Document NameCONFIDENTIALEntity Framework vs. LINQ to SQLTextTextTextTextTextTextTextTextTextTextTextTextDocument NameCONFIDENTIALEF vs. LINQ-to-SQL- 54 - LINQ-to-SQL

Strongly typed LINQ access for RAD against SQL Server only Support s only direct Table-Per-Type (1-to-1) mapping Limited out-of-the box support for complex scenarios

Entity Framework

Designed for larger enterprise applications Enables complex mapping complex scenarios Tools and designer more robust Supports inheritance and many-to-many relationships Supports provider independenceDocument NameCONFIDENTIALEF vs. LINQ-to-SQL- 55 -CategoryLINQ-to-SQLEntity FrameworkModel domain modelconceptual data modelDatabases SupportedSQL server onlySQL server, OracleDB, DB2 and many more Complexity/Learning Curvesimple to usecomplex to useDevelopment Time

rapid developmentslower development but more capabilitiesMappingDirect 1-to-1Custom mappingInheritancehard to applysimple to applyDocument NameCONFIDENTIAL Summary Q & ATextTextTextTextTextTextTextTextTextTextTextTextDocument NameCONFIDENTIALWant more.- 57 - Official site


101 LINQ Samples

Document NameCONFIDENTIALThank YouTextTextTextTextTextTextTextTextTextTextTextTextDocument NameCONFIDENTIAL