1 / 37

Linq

Linq. Overview. Vincent GERMAIN. Evolution - Rappel. Langage C# 2.0 C# 3.0 (Local type inference, Lambda expression, Method extension,Anonymous type). Evolution - Rappel. .NET Framework .NET 2.0 .NET 3.0 (WPF, WCF, WF) .NET 3.5 (AJAX, LINQ). Linq Overview. Introduction

xiu
Download Presentation

Linq

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Linq Overview Vincent GERMAIN

  2. Evolution - Rappel • Langage • C# 2.0 • C# 3.0 (Local type inference, Lambda expression, Method extension,Anonymous type)

  3. Evolution - Rappel • .NET Framework • .NET 2.0 • .NET 3.0 (WPF, WCF, WF) • .NET 3.5 (AJAX, LINQ)

  4. Linq Overview • Introduction • Using Linq To Objects • Using Linq To XML • Using Linq To ADO.NET

  5. Introduction • LINQ : .NET Language Integrated Query • Queries/manipulations of results(from any datasource) • Integrated in .NET Framework • Existing datasources which use Linq : • Linq To ADO.NET • Linq To Object • Linq To XML

  6. Architecture LINQ

  7. Linq To Object • Linq to Objects • LINQ to Objects allows .NET developers to write “queries” over collections of objects • 2 ways to write a linq query: • Query Expression • Extend Method

  8. Linq Syntax int[] nums = new int[] {0,4,2,6,3,8,3,1};   var result = from n in nums where n < 5 select n;     Or var result = nums.Where(n=>n<5);

  9. Linq Operators

  10. Linq To XML • Concept : all with objects XElement xe=new XElement(‘Book1’, new XElement(‘Book2’, new XAttribute(‘type’,’paper’))); • No XSD Intellisense Available in VS2008 XDocument.Element(‘Book1’). Where(e=>e.Attribute(‘type’)==‘paper’);

  11. Linq To ADO.NET • Linq To DataSet • Linq To Entities • Linq To SQL

  12. Linq To SQL • How To use Linq To SQL • Linq To SQL requires 2 things: • Business Classes with Linq Attributes • A DataContext class uses to manage the business Objects(Factory) • Creation(2 methods): • Create a Linq To SQL dbml file with VS2008. The VS 2008 Linq To SQL Item provides automatically the DataContext Class and let you define your business class through drad&drop with the class designer. The Linq Attributes for each object is affected by the designer • Create yours own classes definitions with Linq Attributes(…) & Implement a specific DataContext which herites from LinqContext(.NET Framework Class)

  13. How to Do with Linq(part 1) • Select • Method 1:var query=from u in UserRepository where u.IsAdmin select u; • Method2:var query=UserRepository.Where(u=>u.IsAdmin); • Insert • LinqContext.Users.InsertOnSubmit(user); • Update • User admin=UserRepository.Where(u=>u.IsAdmin).First(); admin.Name=«  Francezinhas»; LinqContext.SubmitChanges(); • Delete • LinqContext.Users.DeleteOnSubmit(user); • LinqContext.Users.DeleteAllOnSubmit(UserRepository);

  14. How To Do with Linq (Part 2) • Paging • var query=list.Skip(200).Take(20); • Sorting • var query=list.OrderBy(c=>c.Name); • Call Stored Procedure • var query=db.getProductById(5);

  15. How To Do With Linq (Part 3) • Transactions • Optimistic Concurrency(default) Try{ … db.submitChanges(); }catch(ChangeConflitException){ db.Resolve/db.ResolveAll } • Pessimistic Concurrency Using(TransactionScope tr=new TransactionScope()){ .. db.SubmitChanges(); tr.Complete(); }

  16. How To Do With Linq (Part 4) • Datasource binding • LinqDataSource

  17. Linq Advantages & Architecture Vincent GERMAIN

  18. Linq Overview • Why Linq ? • Linq Issues • Take advantage of Linq: Queries Construction • Linq Architectures • Benchmarks

  19. Why Linq (Part 1)? ADO.NET Standard Raptier / Code Smith Linq To SQL UI.Web User u=userController.GetUser(12); u.name= « Francezinhas » userController.Save(u); User u=userController.GetUser(12); u.name= « Francezinhas » userController.Save(u); User u=userController.GetUser(12); u.name= « Francezinhas » userController.Save(u); BLL Public class userController{ Public static User GetUser(int id) UserFactory.Get(id); Public static void Save(User u) UserFactory.Save(u); } Public class userController{ Public static User GetUser(int id) UserFactory.Get(id); Public static void Save(User u) UserFactory.Save(u); } Public class userController{ Public static User GetUser(int id) UserFactory.Get(id); Public static void Save(User u) UserFactory.Save(u); } Many factories Many factories One factory DAL Public class userFactory{ Public static User GetUser(int id) SqlCommand cmdGet… Public static void Save(User u) SqlCommand cmdUpdate… } Public class userFactory{ Auto-generated + Custom Queries } Public class LinqContext{ Auto-generated }

  20. Why Linq (Part 2)? • Integrate to .Net Framework 3.5 (no install required except VS2008) • No Datasource queries language required. • Datasource modification can be perform without application code review/change. • No more mistakes in query / security (SQL Injection with parameters). • More simple for basic operations (CRUD, paging, sorting, filters…). • Queries checked at compilation. • Object relationship accessible without coding. • Differed Methods for Queries construction

  21. Linq To SQL Issues • Works only with SQL Server ! (Except Linq To Entities) • Serialization • VS2008 DB changes Integration • Changes tracker • Grid Sorting • Factory/BE separation • Limitation SQL (Like/in) • Loss of Performance (abstraction, interop…)

  22. Linq To SQL Queries construction ADO.NET Standard Raptier / Code Smith Linq To SQL DAL BLL Public class OrderFactory{ static IList GetOrders(){ sql=‘select * from Orders where IsVisible=1’ return GetToList(cmd) } static IList GetOrderSales(){ sql=‘select * from Orders where IsVisible=1 and Type=1’ return GetToList(cmd) } static IList GetOrderSalesByName(n){ sql=‘select * from Orders where IsVisible=1 and Type=1 and name like’%’+n’%’’ return GetToList(cmd); } } Public class OrderFactory{ static Order[] GetOrders(){ return GetAsArray(‘IsVisible=1’); } static Order[] GetOrderSales(){ return GetAsArray(‘IsVisible=1 and Type=1’); } static Order] GetOrderSalesByName(n){ return GetAsArray(‘IsVisible=1 and Type=1 and name like’%’+n+’%’’); } } Public class OrderController{ IQueryable<> GetOrders(){ return LinqContext.Orders. Where(e=>e.IsVisible); } IQueryable<> GetOrderSales(){ return GetOrders(). Where(e=>e.Type==1); } IQueryable<> GetOrderSalesByName(s){ return GetOrderSales(). Where(e=>e.Name.Contains(s); } }

  23. Linq to SQL – Deferred/Nondeferred Operators • Conversion (ToArray, ToList, ToDictionary, ToLookup) • Equality (SequenceEqual) • Element (First, Last, Single, ElementAt) • Quantifiers (Any, All, Contains) • Aggregate (Count,Sum, Min, Max, Average, Aggregate) • Restriction (where) • Projection (select) • Partitioning (take, skip) • Concatenation (Concat) • Ordering (OrderBy, Then, Reverse) • Join (Join, GroupJoin) • Grouping (GroupBy) • Set (Distrinct, Union, Intersect, Except) • Conversion (Cast, OfType, AsEnumerable) • Element (DefaultIfEmpty) • Generation (Range, Repeat, Empty)

  24. Linq To SQL Architecture • Pony solution • Independent LinqContext • Transitional LinqContext(Parameter) • UoW(Unit of Work) pattern

  25. Linq Architecture Pony Solution UI.Web using(LinqContext c=new LinqContext()){ User u=LinqContext.Users.Single(c=>c.Id=id); u.name= « Francezinhas »; userController.SubmitChanges(); } DAL Public partial class LinqContext:System.Data.Linq.DataContext{}

  26. Linq Architecture Pony Solution • Simple • Quick • It’s the same as writing SQL in Code-Behind • No Separation between UI & Business • Impossible to use in another part of code (rewrite each time the same code) • Use 1 LinqContext / Method (+/-) • More maintenance

  27. Linq Architecture Independent LinqContext UI.Web User u=userController.GetUser(12); u.name= « Francezinhas » userController.Save(u); BLL Public class userController{ Public static User GetUser(int id){ using(LinqContext c=new LinqContext()) return LinqContext.Users.Single(c=>c.Id=id); } } Public class userController{ Public static void Save(User u){ using(LinqContext c=new LinqContext()){ User oldUser=GetUser(u.Id); LinqContext.Users.Attach(oldUser,u); LinqContext.SubmitChanges(); }}} DAL Public partial class LinqContext:System.Data.Linq.DataContext{}

  28. Linq Architecture Independent LinqContext • Business Rules independent from UI (UI cannot use directly LinqContext) • Use a LinqContext only when required • Only in charge of filling or saving an object (we can change without difficulties the factory. Ex: Raptier factories • Serialization (No Tracker) • Correct destruction of the Context • Bad Performance (Load each time a LinqContext with relationship) • Must detach an object for loading and attach an object to a context for saving (additional queries is needed) • Hard to build a good transaction system (only possible with TransactionScope)

  29. Linq Architecture Transitional LinqContext UI.Web using(LinqContext c=new LinqContext()){ User u=userController.GetUser(c,12); u.name= « Francezinhas » userController.Save(c,u); } BLL Public class userController{ Public static User GetUser(LinqContext lc,int id){ return lc.Users.Single(c=>c.Id=id); } } Public class userController{ Public static void Save(LinqContext lc,User u){ lc.SubmitChanges(); } } DAL Public partial class LinqContext:System.Data.Linq.DataContext{}

  30. Linq Architecture Transitional LinqContext • Business Rules independent from UI • Use a LinqContext only when required in UI and pass it through Methods • Correct destruction of the Context • Easy for transaction • Object manipulation more simple with Object tracker (update, relationship…) • No Serialization available (Tracker On or must be deactivated) • Boring to pass through each methods the Context 

  31. Linq Architecture Unit of Work Pattern UI.Web void Application_BeginRequest(…) { LinqDataContext.Current = new LinqContext(); } User u=userController.GetUser(12); u.name= « Francezinhas » LinqDataContext.Save(); BLL Public class userController{ Public static User GetUser(int id){ return LinqDataContext.Current.Users.Single(c=>c.Id=id); } } Public class LinqDataContext{ public static LinqContext Current; Public static void Save(){ Current.SubmitChanges(); } } DAL Public partial class LinqContext:System.Data.Linq.DataContext{}

  32. Linq Architecture Unit of Work Pattern • Only one LinqContext used by user and request • Correct destruction of the Context (in Application_EndRequest) • Easy for transaction • Object manipulation more simple with Object tracker (update, relationship…) • No Serialization available (Tracker On or must be deactivated) • Common LinqContext cannot be used when using Thread (Web application)

  33. Linq Architecture Conclusion

  34. Benchmarks

  35. Benchmarks

  36. Conclusion

More Related