Successfully reported this slideshow.

ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo

647 views

Published on

ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo

Published in: Education, Technology
  • Be the first to comment

ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo

  1. 1.  Jose A. BlakeleyPartner ArchitectMicrosoft Corporation Michael PizzoPrincipal ArchitectMicrosoft Corporation
  2. 2. 
  3. 3.  ADO.NET 1.0 Building a Data Platform The ADO.NET Entity Framework
  4. 4. 
  5. 5. 
  6. 6. 
  7. 7. 
  8. 8. 
  9. 9.  Evolution of Data Access APIs Getting Data from a SQL Database Working with Data ADO.NET and XML Building a Data Platform The ADO.NET Entity Framework
  10. 10. Managed ProviderDataReaderCommandConnectionControls,Designers,Code-gen, etcDataSetDataAdapterXmlReaderXmlWriterOLTP operations,Programmatic Processing,Frameworks
  11. 11. ADO.NET Data ProviderDatastoreDataProviderConnectionCreateCommand()ExecuteReader()DataReaderCommand ParametersParametersParameters
  12. 12. DataSet DataSetTablesTableColumnsColumnConstraintsConstraintRowsRowRelationsRelation
  13. 13. 
  14. 14. DatastoreDataAdapterMappingsMappingsMappingsInsertCommandUpdateCommandDeleteCommandSelectCommandFill() Update()DataSet
  15. 15. 
  16. 16.  Evolution of Data Access APIs ADO.NET 1.0 Building a Data Platform Why a Conceptual Model? The Microsoft Entity Data Model Entity SQL The ADO.NET Entity Framework
  17. 17. Programming Data is Hard
  18. 18. Increase Developer Productivity
  19. 19. 
  20. 20.  The Need… Applications work with a wellDefined Model Storage Schema Abstraction Declarative mapping betweenapplication and storage models No brittle, hard-coded mapping
  21. 21. SalesPersonEmployeeID = 729742LoginID = peteTitle = "Developer"VacationHours = 0…ExpenseAccount = …CarLicenseNum = ……SalesPersonEmployeeID = 729742LoginID = peteTitle = "Developer"VacationHours = 0…ExpenseAccount = …CarLicenseNum = ……SalesPersonEmployeeID = 729742LoginID = peteTitle = "Developer"VacationHours = 0…ExpenseAccount = true…SalesPersonEmployeeID = 294272LoginID = adamTitle = "Dev Lead"VacationHours = 0…ReportsManager11N
  22. 22. 
  23. 23.  Data Access in the 80s ADO.NET 1.0 Building a Data Platform Entity Designer EntityClient Object Services
  24. 24.  Data Access in the 80s ADO.NET 1.0 Building a Data Platform The ADO.NET Entity Framework Overview EntityClient Object Services
  25. 25. 
  26. 26. 
  27. 27.  Data Access in the 80s ADO.NET 1.0 Building a Data Platform The ADO.NET Entity Framework Overview Entity Designer Object Services
  28. 28. 
  29. 29.  Data Access in the 80s ADO.NET 1.0 Building a Data Platform The ADO.NET Entity Framework Overview Entity Designer EntityClient
  30. 30. 
  31. 31. 
  32. 32. 
  33. 33. // 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 Customerswhere c.Discount >= 3.0 && c.Discount < 4.0select new { c.Name, Perc = c.Discount / 100.0 };
  34. 34.  Introduction to LINQ LINQ to Entities LINQ to DataSet
  35. 35. DirectMapping
  36. 36. StronglytypedSQLDatabase
  37. 37. Features
  38. 38.  Introduction to LINQ LINQ to SQL LINQ to DataSet
  39. 39. FlexibleMappingtoRelationalData•••••••••
  40. 40. Features
  41. 41.  Introduction to LINQ LINQ to SQL LINQ to Entities
  42. 42. LINQoverDisconnectedCachewithChangeTracking
  43. 43. TypedandUnTyped AsEnumerable() Field<T>(columnName)var query = from row in myDataSet.Tables["Customers"].AsEnumerable()where row .Field<string>("City") == "London"select new { row.Field <string> ("CustomerID"),row.Field <string> ("ContactName") } ;var query = from customer in northwind.Customerswhere customer.City == "London"select customer; Typed DataSet Use strongly typed accessors
  44. 44. 
  45. 45. 
  46. 46. Customizing Data Classes
  47. 47.  Customizing Data Classes Entity Framework Mapping Scenarios Core Mapping Scenarios Function Mapping Mapping Limitations Database Design Considerations Advanced Mapping Techniques
  48. 48. 
  49. 49. 
  50. 50. 
  51. 51. 
  52. 52.  Customizing Data Classes Entity Framework Mapping Scenarios Database Design Considerations
  53. 53. 
  54. 54. <Schema Namespace="AdventureWorksModel" Alias="Self"xmlns="http://schemas.microsoft.com/ado/2006/04/edm"><EntityContainer Name="AdventureWorksEntities"><EntitySet Name="Contacts"EntityType="AdventureWorksModel.Contact" /><AssociationSet Name="ManagerEmployees"Association="AdventureWorksModel.ManagerEmployee"><End Role="Employees" EntitySet="Contacts" /><End Role="Manager" EntitySet="Contacts" /></AssociationSet></EntityContainer><EntityType Name="Contact"><Key><PropertyRef Name="ContactID" /></Key><Property Name="ContactID" Type="Int32" Nullable="false" /><Property Name="Title" Type="String" /><Property Name="FirstName" Type="String" Nullable="false" /><Property Name="LastName" Type="String" Nullable="false" /></EntityType><Association Name="ManagerEmployee"><End Role="Employees"Type="AdventureWorksModel.Employee" Multiplicity="*" /><End Role="Manager"Type="AdventureWorksModel.Employee" Multiplicity="0..1" /></Association></Schema>
  55. 55. <Schema Namespace="AdventureWorksModel.Store" Alias="Self"Provider="System.Data.SqlClient" ProviderManifestToken="2008"xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator"xmlns="http://schemas.microsoft.com/ado/2006/04/edm/ssdl"><EntityContainer Name="HumanResources"><EntitySet Name="Contact"EntityType="AdventureWorksModel.Store.Contact" Schema="Person" /><AssociationSet Name="FK_Employee_Employee_ContactID"Association= "AdventureWorksModel.Store.FK_Employee_Employee_ContactID"><End Role="Employees" EntitySet="Employee" /><End Role="Manager" EntitySet="Employee" /></AssociationSet></EntityContainer><EntityType Name="Contact"><Key><PropertyRef Name="ContactID" /></Key><Property Name="ContactID" Type="int" Nullable="false" StoreGeneratedPattern="Identity" /><Property Name="Title" Type="nvarchar" /><Property Name="FirstName" Type="nvarchar" Nullable="false" /><Property Name="LastName" Type="nvarchar" Nullable="false" /></EntityType><Association Name="FK_Employee_Employee_ContactID"><End Role="Employees" Type="AdventureWorksModel.Store.Employee" Multiplicity="*" /><End Role="Manager" Type="AdventureWorksModel.Store.Employee" Multiplicity="0..1" /></Association></Schema>
  56. 56. <Mapping Space="C-S" xmlns="urn:schemas-microsoft-com:windows:storage:mapping:CS"><EntityContainerMapping StorageEntityContainer="HumanResources"CdmEntityContainer="AdventureWorksEntities"><EntitySetMapping Name="Contacts"TypeName="AdventureWorksModel.Contact" StoreEntitySet="Contact"><ScalarProperty Name="ContactID" ColumnName="ContactID" /><ScalarProperty Name="Title" ColumnName="Title" /><ScalarProperty Name="FirstName" ColumnName="FirstName" /><ScalarProperty Name="MiddleName" ColumnName="MiddleName" /><ScalarProperty Name="LastName" ColumnName="LastName" /></EntitySetMapping><AssociationSetMapping Name="ManagerEmployees"TypeName="AdventureWorksModel.ManagerEmployee" StoreEntitySet="Employee"><EndProperty Name="Employees"><ScalarProperty Name="ContactID" ColumnName="ContactID" /></EndProperty><EndProperty Name="Manager"><ScalarProperty Name="ContactID" ColumnName="ManagerID" /></EndProperty><Condition ColumnName="ManagerID" IsNull="false" /></AssociationSetMapping></EntityContainerMapping></Mapping>
  57. 57.  Customizing Data Classes Entity Framework Mapping Scenarios Database Design Considerations Advanced Mapping Techniques Anatomy of an .edmx file Custom Mapping
  58. 58. <ComplexType Name ="FullName"><Property Name="Title" Type="String" /><Property Name="FirstName" Type="String" Nullable="false" /><Property Name="MiddleName" Type="String" /><Property Name="LastName" Type="String" Nullable="false" /></ComplexType><EntityType Name="Contact"><Key><PropertyRef Name="ContactID" /></Key><Property Name="ContactID" Type="Int32" Nullable="false" /><Property Name="Name" Type="Self.FullName" Nullable="false"/><!-- … --></EntityType> Use your ComplexType in your Entities Map the Complex Type in your MSL<EntitySetMapping Name="Contacts" TypeName="AdventureWorksModel.Contact"StoreEntitySet="Contact"><ScalarProperty Name="ContactID" ColumnName="ContactID" /><ComplexProperty Name="Name"><ScalarProperty Name="Title" ColumnName="Title" /><ScalarProperty Name="FirstName" ColumnName="FirstName" /><ScalarProperty Name="LastName" ColumnName="LastName" /></ComplexProperty></EntitySetMapping>
  59. 59.  Entity Framework Mapping Scenarios Database Design Considerations Customizing Data Classes Advanced Mapping Techniques Anatomy of an .edmx file Complex Types
  60. 60. Customize Conceptual Definition
  61. 61. Customize Mapping Definition
  62. 62. 
  63. 63. 
  64. 64.  ADO.NET and SQL Server Futures Summary:ADO.NETAto Z
  65. 65. 
  66. 66. 
  67. 67. 
  68. 68. 
  69. 69.  DataAccessAcross Tiers Futures
  70. 70. 
  71. 71.  Simple programming model Strongly typed Reduce client/server round trips Do not cause a statement to recompileCREATE TYPE myTableType AS TABLE(id INT, name NVARCHAR(100),qtyINT);CREATE PROCEDURE myProc (@tvpmyTableType READONLY) ASUPDATE Inventory SETqty += s.qtyFROM Inventory AS i INNER JOIN@tvp AS tvpON i.id = tvp.idGO
  72. 72. TVP Client Stack Support SqlDbType.Structured
  73. 73. ADO.NET Example using DataTableUsing (MyConnection){//Create a data tableDataTable dt = new DataTable(“TVPOrdersDataTable”);dt.Columns.Add(“ProductType”, typeof(string));dt.Columns.Add(“Quantity”, typeof(int));// Add rowsdt.Rows.Add(“Canon Digital Camera”, 20);dt.Rows.Add(“June”, 10);dt.Rows.Add(“Xbox-360”, 8);// Create a command and bind parameterSqlCommand tvp_cmd = newSqlCommand(“sp_UpdataInventory”,MyConnection);SqlParameter tvpParam =tvp_cmd.Parameters.AddWithValue(@OrdersTvp, dt);//Execute commandtvp_cmd.ExecuteNonQuery();
  74. 74. SqlCommand command =new SqlCommand(string.Empty, sqlConnection);command.CommandText = "insert into MoviesRentedvalues(@customerId, @MovieID, @RentalDate,@DueDate)";….// create a parameter for RentalDateSqlParameter rentDateParam = new SqlParameter("RentDate",System.Data.SqlDbType.DateTimeOffset);rentDateParam.Value = DateTimeOffset.Now;command.Parameters.Add(rentDateParam);// create a parameter for DueDateSqlParameter dueDateParam = new SqlParameter("DueDate",System.Data.SqlDbType.DateTimeOffset);dueDateParam.Value = DateTimeOffset.Now.AddDays(7);command.Parameters.Add(dueDateParam);….
  75. 75. // create a command to get the DueDateSqlCommand command =new SqlCommand(String.Empty, sqlConnection);command.CommandText ="select DueDate from MoviesRented where MovieId = @MovieId";…// Execute the DataReader//using (SqlDataReader dataReader = command.ExecuteReader()){if (dataReader.Read() == false){Console.WriteLine("Movie has not been rented");}DateTimeOffset dueDate =dataReader.GetDateTimeOffset (0);Console.WriteLine("Movie due back on : {0}", dueDate);}
  76. 76. 
  77. 77. // Poll for completionIAsyncResult result = cmd.BeginExecuteReader();while(!result.IsCompleted) {// do some work}SqlDataReader reader = cmd.EndExecuteReader(result);// Use a CallbackIAsyncResult result = cmd.ExecuteReader(new AsyncCallback( myDataCallback ));// do other work…// optionally wait using sync objectresult.WaitHandle.WaitOne();public void myDataCallback( IAsyncResult result ) {SqlDataReader reader = cmd.EndExecuteReader(result);}
  78. 78. 
  79. 79. 
  80. 80. public SqlDataReader GetProducts(int Category) {SqlCommand cmd = new SqlCommand("Select ProductName, UnitPrice from Products " +"where CategoryID = @CatID", cnn);cmd.Parameters.Add("@CatID",Category);cmd.Notification = new SqlNotificationRequest(Category.ToString(), // message"myQueue", // message body3000); // timeoutreturn cmd.Execute();}public void WaitForChanges() {SqlCommand cmd = new SqlCommand("Receive message_body from myQueue " +"WITH wait_for_results", cnn);cmd.CommandTimeout = 0;int category = (int)cmd.ExecuteScalar();Console.WriteLine("Category {0} changed.",category);}
  81. 81. public void LoadFromDataReader(IDataReader reader){// Copy the Data to SqlServerSqlBulkCopy bcp =new SqlBulkCopy( connectString );bcp.DestinationTableName = "Customers";bcp.WriteToServer( reader );}
  82. 82. 
  83. 83. SqlConnection cnn = new SqlConnection(connectString);cnn.Open();SqlCommand cmd =new SqlCommand("SELECT p FROM PointTable", cnn );SqlDataReader reader = cmd.ExecuteReader();while( reader.Read() ){Point point=(Point)reader[0];Console.WriteLine("x:{0}, y:{1}", point.x, point.y );}cnn.Close();
  84. 84. AggregatesAVGCHECKSUM_AGGCOUNTCOUNT_BIGMAXMINSTDEVSTDEVPVARVARPString FunctionsASCIICHARCHARINDEXDIFFERENCELEFTLENLOWERLTRIMncharPATINDEXQUOTENAMEREPLACEREPLICATEREVERSERIGHTRTRIMSOUNDEXSPACESTRSTUFFSUBSTRINGUNICODEUPPERMath FunctionsABSACOSASINATANATN2CEILINGCOSCOTDEGREESEXPFLOORLOGLOG10PIPOWERRADIANSRANDROUNDSIGNSINSQRTSQUARETANDate FunctionsDATEADDDATEDIFFDATENAMEDATEPARTDAYGETDATESYSDATETIMESYSUTCDATETIMESYSDATETIMEOFFSETGETUTCDATEMONTHYEARSystem FunctionsDATALENGTHCHECKSUMNEWIDCURRENT_TIMESTAMPCURRENT_USERHOST_NAMEUSER_NAMEISNUMERICISDATE
  85. 85.  DataAccessAcross Tiers ADO.NET and SQL Server
  86. 86. 
  87. 87. 
  88. 88. 
  89. 89. 
  90. 90. © 2008 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing marketconditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation.MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

×