Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sarang S. Datye Microsoft Global Services India Enhancing Developer Productivity - The LINQ way.

Similar presentations


Presentation on theme: "Sarang S. Datye Microsoft Global Services India Enhancing Developer Productivity - The LINQ way."— Presentation transcript:

1 Sarang S. Datye Microsoft Global Services India Enhancing Developer Productivity - The LINQ way.

2 Agenda Comparing ADO.NET with LINQ Introduction Understanding DataContext against IDbConnection DataContext Mapping.NET Objects to SQL Object Attribute Mapping VS Designer, SQLMetal CodeGen tools Using LINQ to perform Insert, Update, Delete DML thru LINQ to SQL Calling Stored Procedures to bind with.NET Objects Using Stored Procedures Enlisting LINQ queries in transactions LINQ Transactions

3 Introduction LINQ = Language INtegrated Queries Query Expression, Lambdas, Extension methods… LINQ to SQL = Managing Relations data as objects using LINQ

4 LINQ to SQL Accessing data today SqlConnection c = new SqlConnection(…); c.Open(); SqlCommand cmd = new SqlCommand( @"SELECT c.Name, c.Phone FROM Customers c WHERE c.City = @p0"); cmd.Parameters.AddWithValue("@p0", "London“); DataReader dr = c.Execute(cmd); while (dr.Read()) { string name = dr.GetString(0); string phone = dr.GetString(1); DateTime date = dr.GetDateTime(2); } dr.Close(); Queries in quotes Loosely bound arguments Loosely typed result sets No compile time checks

5 public class Customer { … } public class Northwind : DataContext { public Table Customers; … } Northwind db = new Northwind(…); var contacts = from c in db.Customers where c.City == "London" select new { c.Name, c.Phone }; LINQ to SQL Accessing data with LINQ Classes describe data Strongly typed connections Integrated query syntax Strongly typed results Tables are like collections

6 LINQ to SQL Language integrated data access Maps tables and rows to classes and objects Builds on ADO.NET and.NET Transactions Mapping Encoded in attributes or external XML file Relationships map to properties Persistence Automatic change tracking Updates through SQL or stored procedures

7 DataContext A DataContext is used to scope changes made to classes defined by LINQ to SQL A DataContext is responsible for keeping references to all LINQ to SQL classes, their properties, and foreign key relationships. A DataContext is not meant to be kept around; we want to create a new context for every “unit of work” to avoid concurrency issues. There are multiple ways to approach this. A DataContext is the API to the database, but at this stage it does not contain any business logic that is not implied by the database schema.

8 DataContext NorthwindDataContext context = new NorthwindDataContext("server=.; database=northwind; integrated security=true");

9 Defining DataContext Inherit from DataContext Override Constructor(s) [Database(Name = “MyDB")] public class MyDataContext : DataContext { public MyDataContext(string connString) : base(connString) { }

10 Creating DataContext Similar to SqlConnection() public static void Main() { string connString = “server=MyServer; database=MyDb”; MyDataContext context = new MyDataContext(connString); : }

11 DataContext Demo

12 LINQ Queries SQL “like” Syntax Not a hack/kludge Built upon Generics Extension methods Lamdas var result = from cust in context.Customers where cust.Location = “Pune” select cust; foreach (Customer c in result) { Console.WriteLine(c.CustomerName); }

13 LINQ Queries LINQ To SQL fetches data from database Populates the Table Object/EntitySet Basic LINQ semantics allows iteration

14 join Query SQL “Like” join Inner join implemented as natural syntax Outer joins thru “DataShapes” var result = from c in Customers join o in Order on c.CustomerID equals o.CustomerID select new { c.CustomerName, o.OrderID } foreach (var v in result) { Console.WriteLine(v); }

15 Outer Joins Use DataShape to associate DataShape shape = new DataShape(); shape.LoadWith (p => p.Address); Context.Shape=shape;

16 JOIN DEMO

17 Inner Joins SELECT [t1].[ASListID], [t1].[QID] FROM [Question] AS [t0] INNER JOIN [QuestionSelection] AS [t1] ON [t0].[QID] = [t1].[QID] WHERE EXISTS( SELECT t3.ASListID FROM [AnswerStep] AS [t2] INNER JOIN [AnswerStepSelection] AS [t3] ON [t2].[ASID] = [t3].[ASID] INNER JOIN [AnswerStepList] AS [t4] ON [t3].[ASListID] = [t4].[ASListID] WHERE ([t3].[ASListID] = [t1].[ASListID]) AND ([t4].[QuestionAreaID] = 1) ) (from t in context.GetTable () join t1 in context.GetTable () on t.TQID equals t1.TQID select new { t1.PSListID, t1.TQID }).Where(n => (from p in context.GetTable () join p1 in context.GetTable () on p.PSID equals p1.PSID join p2 in context.GetTable () on p1.PSListID equals p2.PSListID where ((p2.AuditAreaID == 1)) select p1.PSListID).Contains(n.PSListID));

18 Attribute Mapping Declarative mapping No code required Map Relational to Objects [Table(Name=“prod”)] public class Product { [Column(Name=“ProdId”, IsPrimaryKey=true)] public string ProductID; [Column] public string ProductName; }

19 Attribute Mapping Demo

20 XML Mapping Externalized mapping Can be modified without rebuild Can be generated dynamically

21 Sample xml mapping file

22 XML Mapping Demo

23 Code Generation Tools Attribute and XML can be manually generated CodeGen Tools VS Designer Tool Link to SQL class item Server Explorer Drag and Drop SQLMetal.exe Can generate DBML (Database Markup Language) XML Mapping File Attribute mapped code file (.cs|.vb) VLinq Visual design LINQ Queries http://code.msdn.microsoft.com/vlinq

24 SQLMetal Demo

25 LINQ Associations Mirror database relation in object collection Master-Detail mapping Data available thru Object Collections [Table(Name=“Customers”] Class Customer { [Column] public string CustomerID; [Column]public string CompanyName; [Association(ThisKey=“CustomerID”, OtherKey=“CustomerID”] public EntitySet orders; } [Table(Name=“Orders”)] public class Order { [Column] public string CustomerID; [Column] public stringOrderID; }

26 Association Thru XMLMapping Similar to attribute

27 Association Demo

28 Call StoreProcedures SPs can be mapped thru attributes or XML Call semantics similar to tables Supports parameter passing (in/out) Existing Entity behaviour can be changed to use SPs instead of SQL

29 LINQ to Entities using(AdventureWorksDB aw = new AdventureWorksDB(Settings.Default.AdventureWorks)) { Query newSalesPeople = aw.GetQuery ( "SELECT VALUE sp " + "FROM AdventureWorks.AdventureWorksDB.SalesPeople AS sp " + "WHERE sp.HireDate > @date", new QueryParameter("@date", hireDate)); foreach(SalesPerson p in newSalesPeople) { Console.WriteLine("{0}\t{1}", p.FirstName, p.LastName); } using(AdventureWorksDB aw = new AdventureWorksDB(Settings.Default.AdventureWorks)) { var newSalesPeople = from p in aw.SalesPeople where p.HireDate > hireDate select p; foreach(SalesPerson p in newSalesPeople) { Console.WriteLine("{0}\t{1}", p.FirstName, p.LastName); }

30 LINQ to Entities..contd. LINQ to SQLADO.NET Entities Framework Database SupportSQL ServerMany Object Relational Mapping Capabilities Simple -> 1:1Complex MetadataAttributesedmx file

31 LINQ to DataSets Accessing from the DataSet DataSet ds = new DataSet(); FillOrders(ds); // this method fills the DataSet from a database DataTable orders = ds.Tables["SalesOrderHeader"]; var query = from o in orders.ToQueryable() where o.Field ("OnlineOrderFlag") == true select new { SalesOrderID = o.Field ("SalesOrderID"), OrderDate = o.Field ("OrderDate") }; foreach(var order in query) { Console.WriteLine("{0}\t{1:d}", order.SalesOrderID, order.OrderDate); } Accessing from the DataSet with Joins DataSet ds = new DataSet(); FillOrders(ds); DataTable orders = ds.Tables["SalesOrderHeader"]; DataTable details = ds.Tables["SalesOrderDetail"]; var query = from o in orders.ToQueryable() join d in details.ToQueryable() on o.Field ("SalesOrderID") equals d.Field ("SalesOrderID") where o.Field ("OnlineOrderFlag") == true select new { SalesOrderID = o.Field ("SalesOrderID"), OrderDate = o.Field ("OrderDate"), ProductID = d.Field ("ProductID"), Quantity = d.Field ("OrderQty") }; foreach(var line in query) { Console.WriteLine("{0}\t{1:d}\t{2}\t{3}", line.SalesOrderID, line.OrderDate, line.ProductID, line.Quantity); }

32 Feedback / QnA Your Feedback is Important! Please take a few moments to fill out our online feedback form at: > For detailed feedback, use the form at http://www.connectwithlife.co.in/vtd/helpdesk.aspx Or email us at vtd@microsoft.com Use the Question Manager on LiveMeeting to ask your questions now!

33 Contact (optional slide) Blog Address www.dotnetbetaworks.com Email Address sarang.datye@microsoft.com

34 © 2007 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.


Download ppt "Sarang S. Datye Microsoft Global Services India Enhancing Developer Productivity - The LINQ way."

Similar presentations


Ads by Google