Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sarang S. Datye Microsoft Global Services India

Similar presentations


Presentation on theme: "Sarang S. Datye Microsoft Global Services India"— Presentation transcript:

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

2 Agenda Introduction Comparing ADO.NET with LINQ DataContext
Understanding DataContext against IDbConnection Attribute Mapping Mapping .NET Objects to SQL Object CodeGen tools VS Designer, SQLMetal DML thru LINQ to SQL Using LINQ to perform Insert, Update, Delete Using Stored Procedures Calling Stored Procedures to bind with .NET Objects LINQ Transactions Enlisting LINQ queries in 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
Queries in quotes SqlConnection c = new SqlConnection(…); c.Open(); SqlCommand cmd = new SqlCommand( @"SELECT c.Name, c.Phone FROM Customers c WHERE c.City "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(); Loosely bound arguments Loosely typed result sets No compile time checks

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

6 LINQ to SQL Language integrated data access Mapping Persistence
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<Person>(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<ConsoleApplication3.TailoringQuestion>() join t1 in context.GetTable<ConsoleApplication3.TailoringQuestionSelection>() on t.TQID equals t1.TQID select new { t1.PSListID, t1.TQID }).Where(n => (from p in context.GetTable<ConsoleApplication3.ProgramStep>() join p1 in context.GetTable<ConsoleApplication3.ProgramStepSelection>() on p.PSID equals p1.PSID join p2 in context.GetTable<ConsoleApplication3.ProgramStepList>() 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
<?xml version="1.0" encoding="utf-8"?> <Database Name="northwind" xmlns=" <Table Name="dbo.Customers" Member="Customers"> <Type Name="Customer"> <Column Name="CustomerID" Member="CustomerID" Storage="_CustomerID" DbType="NChar(5) NOT NULL" CanBeNull="false" IsPrimaryKey="true" /> <Column Name="CompanyName" Member="CompanyName" Storage="_CompanyName" DbType="NVarChar(40) NOT NULL" CanBeNull="false" /> </Type> </Table> </Database>

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

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<Order> orders; } [Table(Name=“Orders”)] public class Order [Column] public stringOrderID;

26 Association Thru XMLMapping
Similar to attribute <?xml version="1.0" encoding="utf-8"?> <Database Name="northwind" xmlns=" <Table Name="dbo.Customers" Member="Customers"> <Type Name="Customers"> <Column Name="CustomerID" Member="CustomerID" Storage="_CustomerID" DbType="NChar(5) NOT NULL" CanBeNull="false" IsPrimaryKey="true" /> <Column Name="CompanyName" Member="CompanyName" Storage="_CompanyName" DbType="NVarChar(40) NOT NULL" CanBeNull="false" /> <Association Name="FK_Orders_Customers" Member="Orders" Storage="_Orders" ThisKey="CustomerID" OtherKey="CustomerID"/> </Type> </Table> <Table Name="dbo.Orders" Member="Orders"> <Type Name="Orders"> <Column Name="OrderID" Member="OrderID" Storage="_OrderID" DbType="Int NOT NULL IDENTITY" IsPrimaryKey="true" IsDbGenerated="true" AutoSync="OnInsert" /> <Column Name="CustomerID" Member="CustomerID" Storage="_CustomerID" DbType="NChar(5)" /> <Column Name="OrderDate" Member="OrderDate" Storage="_OrderDate" DbType="DateTime" /> </Database>

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<SalesPerson> newSalesPeople = aw.GetQuery<SalesPerson>( "SELECT VALUE sp " + "FROM AdventureWorks.AdventureWorksDB.SalesPeople AS sp " + "WHERE sp.HireDate new 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 SQL ADO.NET Entities Framework
Database Support SQL Server Many Object Relational Mapping Capabilities Simple -> 1:1 Complex Metadata Attributes edmx file

31 LINQ to DataSets 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<int>("SalesOrderID") equals d.Field<int>("SalesOrderID") where o.Field<bool>("OnlineOrderFlag") == true select new { SalesOrderID = o.Field<int>("SalesOrderID"), OrderDate = o.Field<DateTime>("OrderDate"), ProductID = d.Field<int>("ProductID"), Quantity = d.Field<short>("OrderQty") }; foreach(var line in query) { Console.WriteLine("{0}\t{1:d}\t{2}\t{3}", line.SalesOrderID, line.OrderDate, line.ProductID, line.Quantity); } 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<bool>("OnlineOrderFlag") == true select new { SalesOrderID = o.Field<int>("SalesOrderID"), OrderDate = o.Field<DateTime>("OrderDate") }; foreach(var order in query) { Console.WriteLine("{0}\t{1:d}", order.SalesOrderID, order.OrderDate); }

32 Feedback / QnA Your Feedback is Important!
Please take a few moments to fill out our online feedback form at: << Feedback URL – Ask your organizer for this in advance>> For detailed feedback, use the form at Or us at Use the Question Manager on LiveMeeting to ask your questions now!

33 Contact (optional slide)
Blog Address Address

34


Download ppt "Sarang S. Datye Microsoft Global Services India"

Similar presentations


Ads by Google