Presentation is loading. Please wait.

Presentation is loading. Please wait.

Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer)

Similar presentations


Presentation on theme: "Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer)"— Presentation transcript:

1 Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer) fons.sonnemans@reflectionit.nl http://www.reflectionit.nl

2 2 Agenda C# 3.0 LINQ LINQ to SQL Entity Framework

3 3 ADO.NET Problems using (SqlConnection c = new SqlConnection( … )) { c.Open(); string sql ="SELECT c.Name, c.Phone, c.CreationDate " + "FROM Customers c " + "WHERE c.City= @p0" SqlCommand cmd = new SqlCommand(sql, c); cmd.Parameters.AddWithValue("@p0", "London"); SqlDataReader dr = c.ExecuteReader(cmd); while(dr.Read()) { string name = dr.GetString(0); string phone = dr.GetString(1); DateTime date = dr.GetDateTime(2); … } Queries in quotes Loosely bound arguments Loosely typed resultsets No compiletime checking No IntelliSense

4 Reflection IT C# 3.0

5 5 C# 3.0: Local Variable Type Inference Local variable type inference is a feature in C# 3.0 where you can use the var keyword instead of explicitly specifying the type of a variable. The C# 3.0 compiler makes the type of the variable match the type of the right side of the assignment. public void Foo() { var i = 5; var s = "Hello"; var d = 1.0; var z;// compiler error, no initializer z = DateTime.Today; }

6 6 C# 3.0: Object Initializers public class Point { private int x, y; public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } } Point a = new Point { X = 0, Y = 1 }; Point a = new Point(); a.X = 0; a.Y = 1; Field or property assignments

7 7 C# 3.0: Anonymous Types Different anonymous object initializers that define properties with same names in the same order generate the same anonymous type var emp = new { Name = "Fons", Salary = 2000, DateTime.Today.Year }; var year = emp.Year; class XXX { public string Name { get; set; } public int Salary { get; set; } public int Year { get; set; } }

8 8 C# 3.0: Extension Methods Extend existing types with additional methods. namespace MyStuff { public static class Util { public static bool IsWeekend(this DateTime value) { return (value.DayOfWeek == DayOfWeek.Sunday || value.DayOfWeek == DayOfWeek.Saturday); } using MyStuff; Brings extensions into scope dt.IsWeekend()  DateTime.IsWeekend(dt) DateTime dt = DateTime.Today; bool b = dt.IsWeekend();

9 9 C# 3.0: Lambda Expressions delegate string SomeDelegate(string s); private static string TestMethod1(string s) { return s.ToUpper(); } … SomeDelegate d1 = new SomeDelegate(TestMethod1); string a = d1("abcde"); SomeDelegate d3 = delegate(string s) { return s.ToUpper(); }; string a = d3("abcde"); SomeDelegate d4 = s => s.ToUpper(); string a = d4("abcde"); C# 1.0C# 2.0C# 3.0 SomeDelegate d2 = TestMethod1; string a = d2("abcde"); C# 2.0 Delegate Inference Anonymous Method Lambda Expression OO Function- Pointer

10 Reflection IT LINQ Language-Integrated Query

11 11 What is LINQ? Uniform way to write queries over data  Data == Objects  Imperative  Declarative  Works against objects, relational and XML LINQ is about query keywords  Built into new languages C# 3.0 and VB 9.0 LINQ is about query operators  40+ standard query operators are defined  Methods that operate in queries or act on its results

12 12 C# 3.0: Query Expressions from id in source { from id in source | join id in source on expr equals expr [ into id ] | let id = expr | where condition | orderby ordering, ordering, … } select expr | group expr by key [ into id query ] Starts with from Zero or more from, join, let, where, or orderby Ends with select or group by Optional into continuation

13 13 from c in customers where c.State == "WA" select new { c.Name, c.Phone }; customers.Where(c => c.State == "WA").Select(c => new { c.Name, c.Phone }); C# 3.0: Query Expressions Queries translate to method invocations  Where, Join, OrderBy, Select, GroupBy, …

14 14 Language-Integrated Query Others… VB C# LINQ Provider ADO.NET Based LINQ To Datasets LINQ To SQL LINQ To Entities LINQ To XML LINQ To Objects Objects XML Relational

15 15 Two kinds of LINQ Enumerable typesQueryable types ExecutionLocal in-memoryUsually remote ImplementationIterators using yield return Expression tree parsing Interface IEnumerable IQueryable ProvidersLINQ to ObjectsLINQ to SQL LINQ to Entities Other APIsLINQ to XML LINQ to DataSets

16 16 Standard Query Operators RestrictionWhere ProjectionSelect, SelectMany OrderingOrderBy, OrderByDescending, ThenBy, ThenByDecending GroupingGroupBy QuantifiersAny, All, Contains PartitioningTake, Skip, TakeWhile, SkipWhile SetsDistinct, Union, Concat, Intersect, Except ElementsFirst, FirstOrDefault, Last, Single, ElementAt AggregationCount, Sum, Min, Max, Average ConversionToArray, ToList, ToDictionary, ToLookup CastingCast, OfType

17 17 LINQ to Objects

18 18 LINQ to SQL O/R Mapper  Maps.NET classes to relational SQL Server data Translates LINQ queries to SQL execution Supports change tracking for insert, update, delete operations Built on top of ADO.NET and integrates with connection-pooling and transactions

19 19 LINQ to SQL from c in db.Customers where c.City == "London" select c.CompanyName IQueryable<T> SELECT CompanyName FROM Customer WHERE City = 'London' SQL Query or SProc Resultset Objects db.Customers.InsertOnSubmit(c1); c2.City = "Asten"; db.Customers.DeleteOnSubmit(c3); SubmitChanges() INSERT INTO Customer … UPDATE Customer … DELETE FROM Customer … DML or SProcs [Attributes] Application SQL Server LINQ to SQL (DataContext) LINQ to SQL (DataContext)

20 20 LINQ to SQL

21 Reflection IT ADO.NET Entity Framework Included in Visual Studio SP1

22 22 ADO.NET Entity Framework O/R Mapper  Maps.NET classes to relational SQL data Translates LINQ and Entity SQL queries to SQL execution Supports change tracking for insert, update, delete operations Built on top of ADO.NET and integrates with connection-pooling and transactions

23 23 ADO.NET Entity Framework RDBMS Datastore Objects Schema Datastore Objects Schema Entity Data Model Schema Entity Data Model Schema Conceptual ModelStorage/Logical Model *.CSDL *.MSL *.SSDL Map ObjectConnection ObjectCommand ObjectDataReader ObjectConnection ObjectCommand ObjectDataReader EntityClient (ADO.NET API ) SQL Server Providers Oracle DB2 Object Services (ORM API) ObjectContext EntityObject ObjectContext EntityObject ObjectQueries Entity SQL DataReaderLINQ ObjectsEntity SQL Objects Entity Data Model  Abstraction over a relational database  Consists of conceptual & logical models  Provides mapping layer between conceptual model and logical model Entity Client  Provides classes similar to ADO.NET Providers  Can return results as DbDataReaders Entity SQL  Textual SQL language for dynamic queries Object Services  Enables you to work with object instances  Provides persistence and change tracking LINQ to Entities  Provides LINQ syntax and strongly- typed objects for queries over EDM Entity Data Model

24 24 Entity Data Model The edmx file is composed of three important parts: The csdl section which describes your entities The ssdl section which describes your database The msl section which do the mapping between the two others RDBMS (tables, views, SP’s, FN’s) RDBMS (tables, views, SP’s, FN’s) OO Classes (Properties + Methods) OO Classes (Properties + Methods) Datastore Objects Schema Datastore Objects Schema Entity Data Model Schema Entity Data Model Schema Conceptual ModelStorage/Logical Model *.CSD L *.MSL *.SSD L Map

25 25 Mapping Examples Store Customer CustomerId First Last EntitiesMapping Customers ID FirstName LastName IsPremium Overdraft AccountManager PremiumCustomer Overdraft AccountManager ? ?

26 26 Mapping Examples Store Good Customers ID FirstName LastName Bad Customers ID ForeName Surname Customers CustomerId First Last Type Entities Mapping Type=“G” Type=“B”

27 27 LINQ to Entity Framework from c in db.Customers where c.City == "London" select c.CompanyName IQueryable<T> SELECT CompanyName FROM Customer WHERE City = 'London' SQL Query or SProc Resultset Objects db.AddToCustomer(c1); c2.City = "Asten"; db.DeleteObject(c3); SaveChanges() INSERT INTO Customer … UPDATE Customer … DELETE FROM Customer … DML or SProcs.edmx File (Models & Mapping) Application RDBMS LINQ to EF (ObjectContext) LINQ to EF (ObjectContext)

28 28 Entity SQL (SELECT only) // Object Services using (NorthwindEntities db = new NorthwindEntities()) { // Entity SQL var q = db.CreateQuery ("SELECT VALUE p FROM NorthwindEntities.Products AS p " + "WHERE p.UnitPrice > @price", new ObjectParameter("price", 60)); foreach (var prod in q) { Console.WriteLine(prod.ProductName); } // Entity Client using (EntityConnection con = new EntityConnection("name=NorthwindEntities")) { con.Open(); // Entity SQL EntityCommand cmd = new EntityCommand("SELECT p.ProductName FROM NorthwindEntities.Products" + " AS p WHERE p.UnitPrice > @price", con); cmd.Parameters.AddWithValue("price", 60); using (EntityDataReader r = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) { while (r.Read()) { Console.WriteLine(r["ProductName"]); }

29 29 EF Providers in Progress VendorDB Support MicrosoftSQL Server Core LabOracle, MySQL, PostgreSQL, SQLite IBMDB2, Informix Dynamic Server MySQL ABMySQL NpgsqlPostgreSQL OpenLinkMany via OpenLink ODBC or JDBC PhoenixSQLite DataDirectOracle, Sybase, SQL Server, DB2 Firebird

30 30 LINQ to SQL vs Entity Framework LINQ to SQLADO.NET Entities Framework Database SupportSQL ServerMany Object Relational Mapping Capabilities Simple -> 1:1Complex MetadataAttributesedmx file StatusReleasedBeta, Summer 2008

31 31 ADO.NET Entity Framework

32 32 Summary LINQ is a really important technology Native query integration within languages improves productivity and error checking LINQ to SQL and ADO.NET Entity Framework are both O/R Mappers Using LINQ in ASP.NET is both easy and fun

33 33 Resources http://www.datadeveloper.net/ http://code.msdn.microsoft.com/adonetefx http://msdn.microsoft.com/en- us/netframework/aa904594.aspx http://msdn.microsoft.com/en- us/netframework/aa904594.aspx http://blogs.msdn.com/adonet/default.aspx Visual Studio 2008 Upgrade Training  http://www.reflectionit.nl/Training/default.aspx#orcas http://www.reflectionit.nl/Training/default.aspx#orcas

34 34 Questions mailto:fons.sonnemans@reflectionit.nl http://www.reflectionit.nl http://www.objectmap.nl


Download ppt "Reflection IT LINQ & Entity Framework Fons Sonnemans (Trainer)"

Similar presentations


Ads by Google