Your SlideShare is downloading. ×
Introduction to Linq & Entity Framework
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Introducing the official SlideShare app

Stunning, full-screen experience for iPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Introduction to Linq & Entity Framework

3,873
views

Published on

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

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

Published in: Technology

0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
3,873
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
82
Comments
0
Likes
4
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Introduction
    To LINQ &
    Entity Framework
    Twitter Hashtags:
    #NOLtraining#LINQ #EF
    @nalbadia
  • 2. What is ADO.Net?
    The data access classes for the .Net framework
    Designed for highly efficient data access
    Support for XML and disconnected record sets
  • 3. Where does ADO sit?
    VB
    C#
    C++
    Jscript

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