mysql, linq and the ado.net entity framework

of 32 /32
Presented by, MySQL & O’Reilly Media, Inc. MySQL, LINQ and the ADO.NET Entity Framework Reggie Burnett, MySQL David Sceppa, Microsoft

Author: nedra

Post on 16-Jan-2016

32 views

Category:

Documents


4 download

Embed Size (px)

DESCRIPTION

MySQL, LINQ and the ADO.NET Entity Framework. Reggie Burnett, MySQL David Sceppa, Microsoft. Agenda. From DataSets to data access layers Introducing LINQ Using LINQ to access your data The ADO.NET Entity Framework Introducing ADO.NET Data Services Summary. Working with DataSets. - PowerPoint PPT Presentation

TRANSCRIPT

  • AgendaFrom DataSets to data access layersIntroducing LINQUsing LINQ to access your dataThe ADO.NET Entity FrameworkIntroducing ADO.NET Data ServicesSummary

  • Working with DataSetsBasic example

    //Execute a query, retrieve and store the resultsconnectionString = "Data Source=localhost;User ID=...;";commandText = "SELECT CompanyName, City FROM Customers " + "WHERE Country = ?Country";adapter = new MySqlDataAdapter(commandText, connectionString);adapter.SelectCommand.Parameters.AddWithValue("?Country", "Brazil");table = new DataTable();adapter.Fill(table);

    //Display the resultsDataGridView resultsGrid = new DataGridView();resultsGrid.DataSource = table;

    //Submit pending changescommandBuilder = new MySqlCommandBuilder(adapter);adapter.Update(table);

  • Working with DataSetsBenefitRapid development - Designers, wizards, bound controls make it easy to write code and generate user interfaceDrawbacksDevelopers must become SQL experts to build advanced queriesCode becomes more complex when app model and database schema diverge

  • Moving to data access layersFocus on your application modelQueries expressed in terms of app modelClasses track their own changesData access layer responsible forTranslating into SQL queriesReturning results as objectsSubmitting pending changes

  • Moving to data access layersBasic example

    //Partial class to separate data access codepublic class Customer {

    //Add methods to return data public static List GetCustomers(string country) { List results = new List (); MySqlConnection connection = new MySqlConnection(connectString); connection.Open(); MySqlCommand command = new MySqlCommand(queryString, connection); command.Parameters.AddWithValue("?Country", country); MySqlDataReader reader = command.ExecuteReader(); while (reader.Read()) results.Add(Customer.CreateFromReader(reader)); return results; }

    //Support tracking and submitting changes private string origCustomerId, origCompanyName, ...; public void SubmitChanges() { ... }}

  • Moving to data access layersBenefitDivision of labor - Manage data access code separately, only subset of developers need to become SQL gurusDrawbacksData access code quickly gets complexClasses that span multiple tablesHandling inheritance hierarchiesNote: Patterns and frameworks emerge

  • Introducing LINQWhat is LINQ?Stands for Language INtegrated QueryAllows developers to query data structures using SQL-like syntax from within their applications codeIs available to both C# and Visual Basic developers in Visual Studio 2008

  • Introducing LINQLINQ Example - Querying an array//Create an array of integersint[] myarray = new int[] { 49, 28, 20, 15, 25, 23, 24, 10, 7, 34 };

    //Create a query for odd numbersvar oddNumbers = from i in myarray where i % 2 == 1 select i;

    //Display the results of the queryforeach (int i in oddNumbers) Console.WriteLine(i);//Create a query for odd numbers, sortedvar oddNumbers = from i in myarray where i % 2 == 1 orderby i select i;//Create a query for odd numbers, sorted in descending ordervar oddNumbers = from i in myarray where i % 2 == 1 orderby i descending select i;//Create a query for odd numbersvar oddNumbers = from i in myarray where i % 2 == 1 select i;

    //Compose the original query to create a query for odd numbersvar sorted = from i in oddNumbers orderby i descending select i;

  • LINQ-enabled classesCollection classes extendedArrays, Hashtable, List, etc. LINQ to DataSetExtended for untyped and strongly typedLINQ to XMLData access technologiesLINQ to SQLLINQ to Entities

  • AgendaFrom DataSets to data access layersIntroducing LINQUsing LINQ to access your dataThe ADO.NET Entity FrameworkIntroducing ADO.NET Data ServicesSummary

  • LINQ to DataSetDataSet class enhanced to support LINQAvailable via typed and untyped DataSet Dim ordersQuery = From o In dataSet.Orders _ Where o.CustomerID = "ALFKI" _ Select o

    For Each o As NorthwindDataSet.OrdersRow In ordersQuery Console.WriteLine("{0} {1,10:d}", _ o.OrderID, o.OrderDate) Next o

  • LINQ to DataSetBenefitsQuickest way to use LINQ w/ .NET 2.0 feature setSupports query capabilities previously unavailable using a DataSetReturns results as series of DataRows or as anonymous typesLimitationsAll client-side processing

  • BenefitsRapid application development scenariosQuery processing performed at the serverDesigner makes mapping classes to tables simpleLimitationsSupports limited mapping scenariosNo provider model for extensibilityLINQ to SQLBenefitsRapid application development scenariosQuery processing performed at the serverDesigner makes mapping classes to tables simpleLimitationsSupports limited mapping scenarios

  • AgendaFrom DataSets to data access layersIntroducing LINQUsing LINQ to access your dataThe ADO.NET Entity FrameworkIntroducing ADO.NET Data ServicesSummary

  • What is LINQ to Entities?LINQ implementation of the Entity Data ModelWhat is the Entity Data Model?Definition for your application modelMap between app model, database schemaAdvanced mapping scenarios supportedOne entity mapped across multiple tablesMultiple inheritance hierarchy mappingsMany-to-many without "link" table in model

    What is LINQ to Entities?LINQ implementation of the Entity Data Model

    LINQ to Entities

  • LINQ to DataSetDataSet class enhanced to support LINQAvailable via typed and untyped DataSet Dim ordersQuery = From o In dataSet.Orders _ Where o.CustomerID = "ALFKI" _ Select o

    For Each o As NorthwindDataSet.OrdersRow In ordersQuery Console.WriteLine("{0} {1,10:d}", _ o.OrderID, o.OrderDate) Next o

  • LINQ to Entities or LINQ to SQL?LINQ to SQLShipped with Visual Studio 2008 and .NET 3.5Emphasis on rapid application developmentSupports Microsoft SQL Server family of databasesLINQ to EntitiesWill ship as an update to .NET 3.5Offers a provider model for third-party databasesDesigned for enterprise-grade data scenariosHigher level of abstraction for programming databasesJust one layer of the overall ADO.NET Entity Framework

  • LINQ to Entities: Generating QueriesConverting LINQ queries to SQLCompiler converts code into a LINQ expression treeLINQ to Entities converts LINQ expression tree into a DbCommandTree based on mapping informationDbCommandTree expressed in terms of the database schemaADO.NET provider generates a DbCommandLINQ to Entities executes the DbCommand, assembles results into the structure(s) specified in the LINQ query

  • AgendaFrom DataSets to data access layersIntroducing LINQUsing LINQ to access your dataThe ADO.NET Entity FrameworkIntroducing ADO.NET Data ServicesSummary

  • Entity Framework: LINQ and moreADO.NET Entity Framework LayersFirst implementation of Entity Data Model (EDM)Includes a text-based query query language (Entity SQL)New Provider EntityClientNew ORM stack (Object Services) leverages Entity ClientLINQ support over EntitiesAn evolution of ADO.NET preserving customer investment

    ADO.NET ProviderEntityClientObjectServicesLINQ to Entities

  • Entity Framework Query OptionsLINQ to Entities

    Sweet spot:Strongly typed queries and resultsCompile-time type checking and IntellisenseResults returned as objects: entities / projectionsQueries must be well defined at compile time

    var ordersQuery = from o in context.Orders where o.Customers.CustomerID == "ALFKI" select o;

    foreach (var o in ordersQuery) Console.WriteLine("{0} {1:d}", o.OrderID, o.OrderDate);

  • Entity Framework Query OptionsObjectQuery / ObjectQuery(Of T)

    Sweet spot:Strongly typed results, text-based queriesResults returned as objects: entities / projectionsQueries more loosely defined at compile-time

    Dim eql As String = "SELECT VALUE o FROM Orders AS o " & _ " WHERE o.Customer.CustomerID = 'ALFKI'"Dim ordersQuery = context.CreateQuery(Of Order)(esql)

    For Each o As Order In ordersQuery Console.WriteLine("{0} {1,10:d} ", o.OrderID, o.OrderDate)Next o

  • Entity Framework Query OptionsEntityClient Provider

    Sweet spot:Untyped queries and resultsResults returned as DataReadersQueries can be generated purely at run timeNo application model classes needed at compile time

    string eSql = "SELECT VALUE o FROM NorthwindEntities.Orders AS o " + "WHERE o.Customers.CustomerID = 'ALFKI'";EntityCommand cmd = new EntityCommand(eSql, connectionString);EntityDataReader rdr = cmd.ExecuteReader();while (rdr.Read()) Console.WriteLine("{0} {1:d}", rdr["OrderID"], rdr["OrderDate"]);

  • AgendaFrom DataSets to data access layersIntroducing LINQUsing LINQ to access your dataThe ADO.NET Entity FrameworkIntroducing ADO.NET Data ServicesSummary

  • ADO.NET Data ServicesFormerly known as "Project Astoria"Part of ASP.NET Extensions PreviewIntegrated into .NET Framework going forwardTargeting Web development technologiesSilverlight and AJAXData returned via Web-friendly formatsATOM (XML-based) and JSON

  • ADO.NET Data ServicesService exposed via lightweight data access APISupply both location and query as a URI:http://myserver/data.svc/Customers[ALFKI]/OrdersQuery converted to LINQ inside of serviceSupports submitting changesSpecialized Entity Framework logic for submitting changesOnline data hosting service availableFor more information:http://astoria.mslivelabs.com

  • AgendaFrom DataSets to data access layersIntroducing LINQUsing LINQ to access your dataThe ADO.NET Entity FrameworkIntroducing ADO.NET Data ServicesSummary

  • Summary - LINQRepresents a revolution for developersQuery your objects using SQL-like syntaxLINQ to DataSetRich query scenarios for data residing in a DataSetLINQ to EntitiesProvider model for working with other data storesSupports enterprise mapping scenarios

  • Summary - ADO.NET Entity FrameworkMore than just LINQ to EntitiesAlso supports text-based query language ESQLObjectQuery for strongly typed resultsEntityClient for reader-based resultsEnterprise-grade data scenariosProvider model for working with other data stores

  • Summary - ADO.NET Data ServicesDesigned for Silverlight, AJAX environmentsLightweight API, connect and query via URIRetrieve results via familiar formatsATOMJSON

  • Questions?