Download presentation
Presentation is loading. Please wait.
Published byCarlo Iverson Modified over 9 years ago
1
José A. Blakeley Partner Architect Microsoft Corporation Michael Pizzo Principal Architect Microsoft Corporation
10
Managed Provider DataReader Command Connection Controls, Designers, Code-gen, etc DataSet DataAdapter XmlReaderXmlWriter OLTP operations, Programmatic Processing, Frameworks
11
Data store Data Provider Connection CreateCommand() ExecuteReader() DataReader Command Parameters
12
DataSet Tables Table Columns Column Constraints Constraint Rows Row Relations Relation
14
Data store DataAdapter Mappings InsertCommand UpdateCommand DeleteCommand SelectCommand Fill()Update() DataSet
17
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
21
The Need… Applications work with a well Defined Model Storage Schema Abstraction Declarative mapping between application and storage models No brittle, hard-coded mapping
22
SalesPerson EmployeeID = 729742 LoginID = pete Title = "Developer" VacationHours = 0 … ExpenseAccount = … CarLicenseNum = … … SalesPerson EmployeeID = 729742 LoginID = pete Title = "Developer" VacationHours = 0 … ExpenseAccount = … CarLicenseNum = … … SalesPerson EmployeeID = 729742 LoginID = pete Title = "Developer" VacationHours = 0 … ExpenseAccount = true … SalesPerson EmployeeID = 294272 LoginID = adam Title = "Dev Lead" VacationHours = 0 … Reports Manager 1 1 N
40
// Lambda Expressions string[] names = { "Luis", "Mary", "Mike", "Jose" }; Display( names, s => s.Length > 3); // Anonymous Types and object initialization var emp = new { Name = "Mary", Company = "Microsoft", Age = 30 }; // Extension Methods public static class ExtensionMethods { public static void Display (this T[] names, Func filter) { foreach (T s in names) { if (filter(s)) Console.WriteLine(s); } // Query Expressions var query = from c in Customers where c.Discount >= 3.0 && c.Discount < 4.0 select new { c.Name, Perc = c.Discount / 100.0 };
52
var query = from row in myDataSet.Tables["Customers"].AsEnumerable() where row.Field ("City") == "London" where row.Field ("City") == "London" select new { row.Field ("CustomerID"), select new { row.Field ("CustomerID"), row.Field ("ContactName") } ; var query = from customer in northwind.Customers where customer.City == "London" select customer; Typed DataSet Use strongly typed accessors
58
Customizing Data Classes
60
Customizing Data Classes Entity Framework Mapping Scenarios Core Mapping Scenarios Function Mapping Mapping Limitations Database Design Considerations Advanced Mapping Techniques
67
<EntitySet Name="Contacts" EntityType="AdventureWorksModel.Contact" /> <AssociationSet Name="ManagerEmployees" Association="AdventureWorksModel.ManagerEmployee"> <End Role="Employees" Type="AdventureWorksModel.Employee" Multiplicity="*" /> <End Role="Manager" Type="AdventureWorksModel.Employee" Multiplicity="0..1" /> <EntitySet Name="Contacts" EntityType="AdventureWorksModel.Contact" /> <AssociationSet Name="ManagerEmployees" Association="AdventureWorksModel.ManagerEmployee"> <End Role="Employees" Type="AdventureWorksModel.Employee" Multiplicity="*" /> <End Role="Manager" Type="AdventureWorksModel.Employee" Multiplicity="0..1" />
68
<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"> <EntitySet Name="Contact" EntityType="AdventureWorksModel.Store.Contact" Schema="Person" /> <AssociationSet Name="FK_Employee_Employee_ContactID" Association= "AdventureWorksModel.Store.FK_Employee_Employee_ContactID"> <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"> <EntitySet Name="Contact" EntityType="AdventureWorksModel.Store.Contact" Schema="Person" /> <AssociationSet Name="FK_Employee_Employee_ContactID" Association= "AdventureWorksModel.Store.FK_Employee_Employee_ContactID">
69
<EntityContainerMapping StorageEntityContainer="HumanResources" CdmEntityContainer="AdventureWorksEntities"> <EntitySetMapping Name="Contacts" TypeName="AdventureWorksModel.Contact" StoreEntitySet="Contact"> <AssociationSetMapping Name="ManagerEmployees" TypeName="AdventureWorksModel.ManagerEmployee" StoreEntitySet="Employee"> <EntityContainerMapping StorageEntityContainer="HumanResources" CdmEntityContainer="AdventureWorksEntities"> <EntitySetMapping Name="Contacts" TypeName="AdventureWorksModel.Contact" StoreEntitySet="Contact"> <AssociationSetMapping Name="ManagerEmployees" TypeName="AdventureWorksModel.ManagerEmployee" StoreEntitySet="Employee">
71
Use your ComplexType in your Entities Map the Complex Type in your MSL <EntitySetMapping Name="Contacts" TypeName="AdventureWorksModel.Contact" StoreEntitySet="Contact"> <EntitySetMapping Name="Contacts" TypeName="AdventureWorksModel.Contact" StoreEntitySet="Contact">
73
Customize Conceptual Definition
74
Customize Mapping Definition
90
CREATE TYPE myTableType AS TABLE (id INT, name NVARCHAR(100),qty INT); CREATE PROCEDURE myProc (@tvp myTableType READONLY) AS UPDATE Inventory SET qty += s.qty FROM Inventory AS i INNER JOIN @tvp AS tvp ON i.id = tvp.id GO
92
Using (MyConnection){ //Create a data table DataTable dt = new DataTable(“TVPOrdersDataTable”); dt.Columns.Add(“ProductType”, typeof(string)); dt.Columns.Add(“Quantity”, typeof(int)); // Add rows dt.Rows.Add(“Canon Digital Camera”, 20); dt.Rows.Add(“June”, 10); dt.Rows.Add(“Xbox-360”, 8); // Create a command and bind parameter SqlCommand tvp_cmd = new SqlCommand(“sp_UpdataInventory”, MyConnection); SqlParameter tvpParam = tvp_cmd.Parameters.AddWithValue( @OrdersTvp, dt); //Execute command tvp_cmd.ExecuteNonQuery();
94
SqlCommand command = new SqlCommand(string.Empty, sqlConnection); command.CommandText = "insert into MoviesRented values(@customerId,@MovieID, @RentalDate, @DueDate)"; …. // create a parameter for RentalDate SqlParameter rentDateParam = new SqlParameter("RentDate", System.Data.SqlDbType.DateTimeOffset); rentDateParam.Value = DateTimeOffset.Now; command.Parameters.Add(rentDateParam); // create a parameter for DueDate SqlParameter dueDateParam = new SqlParameter("DueDate", System.Data.SqlDbType.DateTimeOffset); dueDateParam.Value = DateTimeOffset.Now.AddDays(7); command.Parameters.Add(dueDateParam); ….
95
// create a command to get the DueDate SqlCommand 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); }
97
// Poll for completion IAsyncResult result = cmd.BeginExecuteReader(); while(!result.IsCompleted) { // do some work } SqlDataReader reader = cmd.EndExecuteReader(result); // Use a Callback IAsyncResult result = cmd.ExecuteReader( new AsyncCallback( myDataCallback )); // do other work… // optionally wait using sync object result.WaitHandle.WaitOne(); public void myDataCallback( IAsyncResult result ) { SqlDataReader reader = cmd.EndExecuteReader(result); }
100
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 body 3000);// timeout return 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); }
101
public void LoadFromDataReader(IDataReader reader) { // Copy the Data to SqlServer SqlBulkCopy bcp = new SqlBulkCopy( connectString ); bcp.DestinationTableName = "Customers"; bcp.WriteToServer( reader ); }
103
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();
104
Aggregates AVG CHECKSUM_AGG COUNT COUNT_BIG MAX MIN STDEV STDEVP VAR VARP String Functions ASCII CHAR CHARINDEX DIFFERENCE LEFT LEN LOWER LTRIM nchar PATINDEX QUOTENAME REPLACE REPLICATE REVERSE RIGHT RTRIM SOUNDEX SPACE STR STUFF SUBSTRING UNICODE UPPER Math Functions ABS ACOS ASIN ATAN ATN2 CEILING COS COT DEGREES EXP FLOOR LOG LOG10 PI POWER RADIANS RAND ROUND SIGN SIN SQRT SQUARE TAN Date Functions DATEADD DATEDIFF DATENAME DATEPART DAY GETDATE SYSDATETIME SYSUTCDATETIME SYSDATETIMEOFFSET GETUTCDATE MONTH YEAR System Functions DATALENGTH CHECKSUM NEWID CURRENT_TIMESTAMP CURRENT_USER HOST_NAME USER_NAME ISNUMERIC ISDATE
114
© 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 market conditions, 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.
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.