• Save
ADO.NET Entity Framework by Jose A. Blakeley and Michael Pizzo
Upcoming SlideShare
Loading in...5
×
 

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

on

  • 524 views

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

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

Statistics

Views

Total Views
524
Views on SlideShare
524
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

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

  •  Jose A. BlakeleyPartner ArchitectMicrosoft Corporation Michael PizzoPrincipal ArchitectMicrosoft Corporation
  • 
  •  ADO.NET 1.0 Building a Data Platform The ADO.NET Entity Framework View slide
  •  View slide
  • 
  • 
  • 
  • 
  •  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
  • Managed ProviderDataReaderCommandConnectionControls,Designers,Code-gen, etcDataSetDataAdapterXmlReaderXmlWriterOLTP operations,Programmatic Processing,Frameworks
  • ADO.NET Data ProviderDatastoreDataProviderConnectionCreateCommand()ExecuteReader()DataReaderCommand ParametersParametersParameters
  • DataSet DataSetTablesTableColumnsColumnConstraintsConstraintRowsRowRelationsRelation
  • 
  • DatastoreDataAdapterMappingsMappingsMappingsInsertCommandUpdateCommandDeleteCommandSelectCommandFill() Update()DataSet
  • 
  •  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
  • Programming Data is Hard
  • Increase Developer Productivity
  • 
  •  The Need… Applications work with a wellDefined Model Storage Schema Abstraction Declarative mapping betweenapplication and storage models No brittle, hard-coded mapping
  • 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
  • 
  •  Data Access in the 80s ADO.NET 1.0 Building a Data Platform Entity Designer EntityClient Object Services
  •  Data Access in the 80s ADO.NET 1.0 Building a Data Platform The ADO.NET Entity Framework Overview EntityClient Object Services
  • 
  • 
  •  Data Access in the 80s ADO.NET 1.0 Building a Data Platform The ADO.NET Entity Framework Overview Entity Designer Object Services
  • 
  •  Data Access in the 80s ADO.NET 1.0 Building a Data Platform The ADO.NET Entity Framework Overview Entity Designer EntityClient
  • 
  • 
  • 
  • // 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 };
  •  Introduction to LINQ LINQ to Entities LINQ to DataSet
  • DirectMapping
  • StronglytypedSQLDatabase
  • Features
  •  Introduction to LINQ LINQ to SQL LINQ to DataSet
  • FlexibleMappingtoRelationalData•••••••••
  • Features
  •  Introduction to LINQ LINQ to SQL LINQ to Entities
  • LINQoverDisconnectedCachewithChangeTracking
  • 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
  • 
  • 
  • Customizing Data Classes
  •  Customizing Data Classes Entity Framework Mapping Scenarios Core Mapping Scenarios Function Mapping Mapping Limitations Database Design Considerations Advanced Mapping Techniques
  • 
  • 
  • 
  • 
  •  Customizing Data Classes Entity Framework Mapping Scenarios Database Design Considerations
  • 
  • <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>
  • <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>
  • <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>
  •  Customizing Data Classes Entity Framework Mapping Scenarios Database Design Considerations Advanced Mapping Techniques Anatomy of an .edmx file Custom Mapping
  • <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>
  •  Entity Framework Mapping Scenarios Database Design Considerations Customizing Data Classes Advanced Mapping Techniques Anatomy of an .edmx file Complex Types
  • Customize Conceptual Definition
  • Customize Mapping Definition
  • 
  • 
  •  ADO.NET and SQL Server Futures Summary:ADO.NETAto Z
  • 
  • 
  • 
  • 
  •  DataAccessAcross Tiers Futures
  • 
  •  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
  • TVP Client Stack Support SqlDbType.Structured
  • 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();
  • 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);….
  • // 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);}
  • 
  • // 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);}
  • 
  • 
  • 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);}
  • public void LoadFromDataReader(IDataReader reader){// Copy the Data to SqlServerSqlBulkCopy bcp =new SqlBulkCopy( connectString );bcp.DestinationTableName = "Customers";bcp.WriteToServer( reader );}
  • 
  • 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();
  • AggregatesAVGCHECKSUM_AGGCOUNTCOUNT_BIGMAXMINSTDEVSTDEVPVARVARPString FunctionsASCIICHARCHARINDEXDIFFERENCELEFTLENLOWERLTRIMncharPATINDEXQUOTENAMEREPLACEREPLICATEREVERSERIGHTRTRIMSOUNDEXSPACESTRSTUFFSUBSTRINGUNICODEUPPERMath FunctionsABSACOSASINATANATN2CEILINGCOSCOTDEGREESEXPFLOORLOGLOG10PIPOWERRADIANSRANDROUNDSIGNSINSQRTSQUARETANDate FunctionsDATEADDDATEDIFFDATENAMEDATEPARTDAYGETDATESYSDATETIMESYSUTCDATETIMESYSDATETIMEOFFSETGETUTCDATEMONTHYEARSystem FunctionsDATALENGTHCHECKSUMNEWIDCURRENT_TIMESTAMPCURRENT_USERHOST_NAMEUSER_NAMEISNUMERICISDATE
  •  DataAccessAcross Tiers ADO.NET and SQL Server
  • 
  • 
  • 
  • 
  • © 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.