Introduction to Linq & Entity Framework

5,155 views

Published on

محاضرة القيتها في الرياض بعنوان: مقدمة في تقنية LINQ & Entity Framework حيث تسهل عليك هذه التقنية من حفظ بياناتك في قواعد البيانات بطريقة سهلة جدا وفي وقت قياسي مقارنة بالطريقة التقليدية

Published in: Technology
0 Comments
6 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
5,155
On SlideShare
0
From Embeds
0
Number of Embeds
1,003
Actions
Shares
0
Downloads
103
Comments
0
Likes
6
Embeds 0
No embeds

No notes for slide

Introduction to Linq & Entity Framework

  1. 1. Introduction<br />To LINQ &<br />Entity Framework<br />Twitter Hashtags: <br />#NOLtraining#LINQ #EF<br />@nalbadia<br />
  2. 2. What is ADO.Net?<br />The data access classes for the .Net framework<br />Designed for highly efficient data access<br />Support for XML and disconnected record sets<br />
  3. 3. Where does ADO sit?<br />VB<br />C#<br />C++<br />Jscript<br />…<br />Common Language Specification<br />ASP.Net<br />Windows Forms<br />Visual Studio .NET<br />ADO.Net<br />XML.Net<br />Base Class Library<br />Common Language Runtime (CLR)<br />Windows<br />COM+ Services<br />
  4. 4. ADO.NET 1.0 Architecture<br />
  5. 5. Connection<br />CreateCommand()<br />Command<br />Parameters<br />Parameters<br />Parameters<br />ExecuteReader()<br />DataReader<br />Data<br />Provider<br />Data <br />store<br />Getting Data From a SQL Database<br />Specific to a particular DBMS<br />Directly exposes consumer interfaces<br />No more COM/Automation dichotomy<br />ADO.NET DataProviderObject Model<br />Connection<br />Establishes connection to DataSource<br />Transaction<br />Explicit Transaction Control<br />Command<br />Execute SQL statement<br />DataReader<br />Forward-only, Read-Only Result Stream<br />Fields accessed through strongly typed, indexed accessors<br />
  6. 6. Data Sources<br />SQL Data Source (SQLConnection) – used to connect natively to SQL Server <br />OLE Data Source (OleDbConnectin) – connect using ole (object linking and embedding technology)<br />ODBC Data Source (OdbcDbConnection) – connect using odbc (Open Database Connectivity )<br />Oracle DataSource (OracleConnection) – connect using oracle driver implementation<br />
  7. 7. .NET Data Providers<br />SQL .NET <br />Data Provider<br />SQLSERVER<br />OLE DB .NET <br />Data Provider<br />OLE DB <br />Provider<br />Client<br />Other DB<br />ODBC .NET <br />Data Provider<br />ODBC <br />Driver<br />Other DB<br />
  8. 8. Data Provider Functionality<br />Client<br />.Net Data Provider<br />Connection<br />Command<br />Rows<br />DataReader<br />DataSet<br />DataAdapter<br />database<br />
  9. 9. ADO.Net object model<br />Fill<br />DataAdapter<br />DataSet<br />Update<br />Errors Collection<br />UpdateCommand<br />SelectCommand<br />InsertCommand<br />DeleteCommand<br />Command<br />Connection<br />Parameters<br />Data Source<br />
  10. 10. Connecting to SQL<br />using System.Data.SqlClient;string sConnectionString = ConfigurationManager.ConnectionStrings["myconnnection"].ConnectionString;SqlDataAdaptersqlAdp= new SqlDataAdapter(sConnectionString);sqlAdp.Close();sqlAdp.Dispose();<br />
  11. 11. Getting data<br />SqlCommandExecuteReaderExecuteNonQueryExecuteScalarExecuteXMLReader<br />SqlDataAdapterDataSet<br />
  12. 12. Using the command object<br />string sSelectQuery = "SELECT * FROM Categories ORDER BY CategoryID";string sConnectionString= ConfigurationManager.ConnectionStrings["myconnnection"].ConnectionString; SqlConnectionobjConnect = new SqlConnection(sConnectString);SqlCommandobjCommand = new SqlCommand(sSelectQuery,objConnect);/*<br />objCommand.CommandTimeout = 15;objCommand.CommandType = CommandType.Text;<br />*/objConnect.Open();SqlDataReaderdrResults;drResults = objCommand.ExecuteReader()drResults.Close();objConnect.Dispose();<br />
  13. 13. The ProblemProgramming Data is Hard<br />Writing queries is difficult<br />No help from compiler<br />Results are untyped rectangular records<br />Database Schemas optimized for storage concerns<br />Relational Tables contain flat, homogenous records<br />Implicit Logic Embedded in Application<br />Brittle, Hard to maintain<br />Lack of common syntax across relational databases<br />
  14. 14. The OpportunityIncrease Developer Productivity<br />Rapid Development<br />Strongly typed queries<br />Strongly typed results with Business Logic<br />Lower TCO<br />Work with an explicit data model<br />Types, Inheritance, Relationships, Complex Properties,…<br />Decouple application from storage schema<br />Better Portability<br />Common query language across disparate sources<br />
  15. 15. Introduction to LINQ<br />Queries as first-class concept in .NET languages<br />Builds on several language features<br />Type inference, Delegates, Generics<br />Enabled by<br />Lambda expressions<br />Anonymous types<br />Object initialization expressions<br />Extension methods<br />Query expressions<br />
  16. 16. Query without LINQ<br />Objects using loops and conditionsforeach(Customer c in customers) if (c.Region == "UK") ...<br />Databases using SQLSELECT * FROM Customers WHERE Region='UK'<br />XML using XPath/XQuery//Customers/Customer[@Region='UK']<br />
  17. 17. ADO without LINQ<br />SqlConnection con = new SqlConnection(...);<br />con.Open(); <br />SqlCommandcmd = new SqlCommand(<br />@"SELECT * FROM Customers<br /> WHERE c.Region = @Region", con<br />);<br />cmd.Parameters.AddWithValue("@Region", "UK"); <br />DataReaderdr = cmd.ExecuteReader(); <br />while (dr.Read()) {<br /> string name = dr.GetString(dr.GetOrdinal("Name"));<br /> string phone = dr.GetString(dr.GetOrdinal("Phone"));<br />DateTime date = dr.GetDateTime(3);<br />}<br />dr.Close();<br />con.Close();<br />
  18. 18. Query with LINQ<br />C#varmyCustomers = from c in customers where c.Region == "UK" select c;<br />VB.NETDim myCustomers = From c In customers _ Where c.Region = "UK" _ Select c<br />
  19. 19. .NET Features<br />// Lambda Expressions<br />string[] names = { "Luis", "Mary", "Mike", "Jose" };<br />Display( names, s => s.Length > 3);<br />// Anonymous Types and object initialization<br />varemp = new { Name = "Mary", Company = "Microsoft", Age = 30 };<br />// Extension Methods<br />public static class ExtensionMethods {<br /> public static void Display<T>(this T[] names, <br />Func<T, bool> filter) {<br />foreach (T s in names) {<br /> if (filter(s)) Console.WriteLine(s);<br /> }<br /> }<br />}<br />// Query Expressions<br />var query = from c in Customers<br /> where c.Discount >= 3.0 && c.Discount < 4.0<br /> select new { c.Name, Perc = c.Discount / 100.0 };<br />
  20. 20. More LINQ queries<br />C#vargoodCusts = (from c in db.Customers where c.PostCode.StartsWith("GY")orderbyc.Sales descending select c).Skip(10).Take(10);<br />VB.NETDim goodCusts = (From c In db.Customers _ Where c.PostCode.StartsWith("GY") _ Order By c.Sales Descending _ Select c).Skip(1).Take(10)<br />
  21. 21. Advantages<br />Unified data accessSingle syntax to learn and remember<br />Strongly typedCatch errors during compilation<br />IntelliSensePrompt for syntax and attributes<br />Bindable result sets<br />
  22. 22. Architecture<br />Others<br />C#<br />VB.NET<br />.NET Language Integrated Query (LINQ)<br />LINQ data source providers<br />ADO.NET support for LINQ<br />LINQto SQL<br />LINQto Objects<br />LINQto XML<br />LINQto Datasets<br />LINQto Entities<br />
  23. 23. LINQ to Objects<br />C#int[] nums = new int[] {0,4,2,6,3,8,3,1};double average = nums.Take(6).Average();var above = from n in nums where n > average select n;<br />VB.NETDim nums() As Integer = {0,4,2,6,3,8,3,1}Double average = nums.Take(6).Average()Dim above = From n In nums _ Where n > average _ Select n<br />
  24. 24. LINQ to Objects<br />Query any IEnumerable<T> sourceIncludes arrays, List<T>, Dictionary...<br />Many useful operators availableSum, Max, Min, Distinct, Intersect, Union<br />Expose your own data with IEnumerable<T> or IQueryable<T><br />Create operators using extension methods<br />
  25. 25. LINQ operators<br />and many others<br />
  26. 26. Demo<br />LINQ<br />
  27. 27. Object Relational Mapping<br />Many ORMs out there<br />No clear “winner” = relatively little adoption of ORM<br />Developers waiting on Microsoft<br />Microsoft shipped two ... hmmm<br />LINQ to SQL in Visual Studio 2008<br />ADO.NET Entity Framework in Visual Studio 2008 SP1<br />
  28. 28. LINQ to SQL<br />Object-relational mappingRecords become strongly-typed objects<br />Data context is the controller mechanism<br />Facilitates update, delete & insert<br />Translates LINQ queries behind the scenes<br />Type, parameter and injection safe<br />
  29. 29. What is the Entity Framework?<br />Create data access applications by programming against a conceptual application model instead of programming directly against a relational storage schema. <br />Decrease the amount of code and maintenance required for data-oriented applications. <br />
  30. 30. What is the Entity Framework?<br />Entity Framework applications provide the following benefits: <br />Applications can work in terms of a more application-centric conceptual model, including types with inheritance, complex members, and relationships.<br />Applications are freed from hard-coded dependencies on a particular data engine or storage schema.<br />Mappings between the conceptual model and the storage-specific schema can change without changing the application code.<br />Developers can work with a consistent application object model that can be mapped to various storage schemas, possibly implemented in different database management systems.<br />Multiple conceptual models can be mapped to a single storage schema.<br />Language-integrated query (LINQ) support provides compile-time syntax validation for queries against a conceptual model. <br />
  31. 31. Where does EF fit with ADO.NET?<br />Object Services provides<br /><ul><li>change management
  32. 32. Works with EntityClient to get and save data
  33. 33. Provides Serialization (XML and Binary)</li></li></ul><li>Where does EF fit with ADO.NET?<br />EntityClient<br />Connects to DBExecutes Commands<br />Retrieves Results<br />Reshapes Results to match model<br />Returns tabular data<br />
  34. 34. Data Access<br />Object Relational<br />Mapping<br />SQL<br />Level of Abstraction<br />Typed<br />DataSet<br />ODBC<br />Entity<br />Framework<br />RDO<br />DataSet<br />OLE DB<br />ADO<br />DAAB<br />ADO.NET<br />(SqlClient)<br />
  35. 35. Entity Framework in a Nutshell<br />class Customer { … }<br />C1<br />C1<br />from c in ctx.Customers<br />where c.Name.StartsWith(“A”)<br />select c<br />C2<br />C2<br />C3<br />C3<br />Entity Framework<br />Model<br />Change Tracking<br />LINQ Translation<br />Materialization<br />Update Pipeline<br />DB<br />
  36. 36. Entity Framework in a Nutshell<br />Goal: Simple and seamless data access for the .NET platform<br />Better layering<br />Better re-use of existing knowledge and assets<br />EDM – Entity Data Model<br />An abstract model for defining entities and relationships<br />Includes schema and mapping<br />Store Schema Definition (SSDL)<br />Conceptual Schema Definition (CSDL)<br />Mapping Schema between the two (MSL)<br />Entity Framework<br />An implementation of EDM and an ORM layer on top<br />A framework for using entities over data<br />
  37. 37. Getting Started<br />Database First (VS 2008 and .NET 3.5 SP1)<br />why? it already exists, or you want low level control over the database<br />DB<br />Model<br />Design time<br />Design time<br />Code<br />Model First (VS 2010 and .NET 4.0)<br />why? you want separation from code and database in a declarative format<br />DB<br />Model<br />Design time<br />Design time<br />Code<br />Code First (Entity Framework Feature CTP3)<br />why? primarily focused on code shape, database is an implementation detail<br />DB<br />Model<br />Runtime<br />Runtime<br />Code<br />
  38. 38. EF Mapping Capabilities<br />Inheritance<br />Table per Hierarchy<br />Table per Type<br />Table per Concrete Type<br />Hybrids<br />Many entities to one table<br />Stored Procedures<br />Many tables to one entity<br />Abstract Entities<br />Associations within EntitySets<br />Associations across EntitySets<br />Store-side discriminators<br />EDM-side discriminators<br />QueryViews, Defining Query, CommandText<br />
  39. 39. Typical Normalized Tables<br />
  40. 40. Generated Entity Data Model<br />
  41. 41. Testability using Entity Framework <br />Why: <br />Test business logic, not database<br />Lightning fast unit tests! <br />How: swap data access code with in-memory test doubles<br />Choice #1: replace repository<br />Choice #2: replace context interface<br />LINQ only<br />Business logic, UI, etc.<br />Real Repository<br />Fake Repository<br />Repository<br />Fake for context interface<br />ObjectContext<br />Database<br />In-memory data<br />In-memory data<br />
  42. 42. Demo<br />Entity Framework<br />
  43. 43. Q & A<br />42<br />

×