ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Enterprise Application Development
    EC-332
    Progress0 / 37 topics
    Topics
    1. Overview of Enterprise Application Development: Microsoft technology history2. Introduction to .NET and its architecture3. Concept of MSIL, CLR, CLS, CTS4. Introduction to .NET framework: Managed and Unmanaged Code5. .Net Assembly6. Introduction to C# fundamentals7. Boxing and Unboxing8. Implementing multi-tier architecture9. Introduction to ADO.Net: SQL Injection, parameterized queries10. Usage of data set, Data adapter and command builder in disconnected model11. Introduction to delegate: Multicast delegates12. Introduction to windows forms13. HTML14. Introduction to javascript: javascript and its data types, variables, functions15. Debugging javascript using Firebug16. Introduction to various object models: Browser's Object (BOM), Document Object Model17. Introduction to Jquery: Jquery effects18. Introducing LINQ: LINQ to Objects, LINQ to SQL19. Query syntax, Operations (projection, filtering and join) using Linq Queries20. Introduction to ADO.NET entity framework: The entity data model, CSDL21. Eager vs lazy loading, POCO classes, DBContext API22. Querying entity data models23. Introduction to ASP.NET MVC24. MVC application structure, Controllers overview25. Action Methods, Parameterized action methods26. Introduction to razor syntax27. Code expressions, Code Blocks, Implicit Vs Explicit Code Expression28. Data annotations, Client and Server Side Validation29. Validation and model binding, Validation and model state30. MVC Membership, Authorization and security31. Introduction to service-oriented architecture: SOAP, WSDL32. Service contract, Data contract, XML, WCF bindings33. ABC of WCF, Restful services34. Consuming rest services (CRUD operations) using Jquery AJAX and JSON35. Introduction to web API36. Example of web API using CRUD Example37. MVC routing
    EC-332›Querying entity data models
    Enterprise Application DevelopmentTopic 22 of 37

    Querying entity data models

    7 minread
    1,146words
    Intermediatelevel

    Querying Entity Data Models in Entity Framework

    Entity Framework (EF) simplifies querying data stored in a relational database by using an Entity Data Model (EDM), which represents data in the form of entities and relationships. EF enables developers to query the database using LINQ (Language Integrated Query), making data access more natural and integrated into the application code.

    Let’s go over the key techniques and examples for querying data in an Entity Data Model (EDM) using Entity Framework.


    1. LINQ to Entities

    LINQ (Language Integrated Query) is a powerful feature of .NET that allows you to query collections in a declarative way. In Entity Framework, LINQ is used to query the entities defined in your Entity Data Model (EDM), and EF will translate the LINQ query into SQL queries that run on the database.

    The most common way to perform LINQ queries in EF is using the DbContext class, which contains DbSet properties representing the entities in your model.


    Basic Querying with LINQ to Entities

    Here’s an example of how you can use LINQ to query an entity in EF.

    using (var context = new MyDbContext())
    {
        // Query all customers
        var customers = from c in context.Customers
                        select c;
        
        foreach (var customer in customers)
        {
            Console.WriteLine($"{customer.CustomerId}: {customer.Name}");
        }
    }
    

    In this example:

    • context.Customers represents the DbSet<Customer> (a collection of Customer entities in the database).
    • The LINQ query retrieves all Customer entities.

    Using LINQ Query Syntax

    LINQ queries can be written using query syntax (like SQL) or method syntax (using LINQ extension methods). Here’s an example of a query using query syntax:

    using (var context = new MyDbContext())
    {
        var customersWithOrders = from c in context.Customers
                                  where c.Orders.Count > 0
                                  select c;
    
        foreach (var customer in customersWithOrders)
        {
            Console.WriteLine($"{customer.Name} has orders.");
        }
    }
    

    This query retrieves customers who have placed at least one order. The where clause filters the customers based on the number of orders.


    Using LINQ Method Syntax

    The same query can be written using method syntax (also known as fluent syntax):

    using (var context = new MyDbContext())
    {
        var customersWithOrders = context.Customers
                                          .Where(c => c.Orders.Count > 0)
                                          .ToList();
    
        foreach (var customer in customersWithOrders)
        {
            Console.WriteLine($"{customer.Name} has orders.");
        }
    }
    

    Both query syntax and method syntax produce the same result, and the choice depends on your coding style preference.


    2. Filtering Data

    To filter data based on conditions, you can use where in LINQ to specify the criteria. For example, to find customers by name:

    using (var context = new MyDbContext())
    {
        var customer = context.Customers
                              .Where(c => c.Name == "John Doe")
                              .FirstOrDefault();  // Fetch the first customer with the name "John Doe"
        
        if (customer != null)
        {
            Console.WriteLine($"Customer found: {customer.Name}");
        }
    }
    

    In this query:

    • Where() filters the Customers based on the condition provided (Name == "John Doe").
    • FirstOrDefault() returns the first matching customer, or null if no customer is found.

    3. Sorting Data

    You can use OrderBy, ThenBy, OrderByDescending, and ThenByDescending to sort your query results. Here's an example of sorting customers by their name:

    using (var context = new MyDbContext())
    {
        var sortedCustomers = context.Customers
                                     .OrderBy(c => c.Name)
                                     .ToList();
    
        foreach (var customer in sortedCustomers)
        {
            Console.WriteLine(customer.Name);
        }
    }
    

    In this example:

    • OrderBy(c => c.Name) sorts customers in ascending order by their name.
    • You can use OrderByDescending for descending order.

    4. Projecting Data (Selecting Specific Columns)

    Instead of fetching entire entities, you can project your query to select specific properties using Select().

    using (var context = new MyDbContext())
    {
        var customerNames = context.Customers
                                   .Select(c => c.Name)  // Only select the Name property
                                   .ToList();
    
        foreach (var name in customerNames)
        {
            Console.WriteLine(name);
        }
    }
    

    In this query:

    • Select(c => c.Name) selects only the Name property from each Customer entity.
    • The result is a list of customer names rather than the full customer objects.

    5. Joining Data

    Entity Framework supports joins between related entities, and you can use LINQ to join data from multiple tables (entities). Here’s an example of how to join Customers and Orders using LINQ:

    using (var context = new MyDbContext())
    {
        var query = from c in context.Customers
                    join o in context.Orders on c.CustomerId equals o.CustomerId
                    select new
                    {
                        CustomerName = c.Name,
                        OrderId = o.OrderId,
                        OrderDate = o.OrderDate
                    };
    
        foreach (var result in query)
        {
            Console.WriteLine($"Customer: {result.CustomerName}, Order: {result.OrderId}, Date: {result.OrderDate}");
        }
    }
    

    In this example:

    • join is used to join the Customers and Orders entities based on the CustomerId field.
    • The result is an anonymous object containing CustomerName, OrderId, and OrderDate.

    6. Aggregation (Count, Sum, Average)

    LINQ also supports aggregation operations such as count, sum, and average. Here’s an example of counting the total number of orders placed by customers:

    using (var context = new MyDbContext())
    {
        var customerOrderCount = context.Customers
                                        .Select(c => new
                                        {
                                            c.Name,
                                            OrderCount = c.Orders.Count()
                                        })
                                        .ToList();
    
        foreach (var result in customerOrderCount)
        {
            Console.WriteLine($"{result.Name} has placed {result.OrderCount} orders.");
        }
    }
    

    This query:

    • Uses Count() to calculate the number of orders each customer has placed.

    7. Grouping Data

    You can also group data using GroupBy() in LINQ. Here’s an example of how to group orders by their year:

    using (var context = new MyDbContext())
    {
        var ordersGroupedByYear = context.Orders
                                         .GroupBy(o => o.OrderDate.Year)
                                         .Select(g => new
                                         {
                                             Year = g.Key,
                                             OrderCount = g.Count()
                                         })
                                         .ToList();
    
        foreach (var group in ordersGroupedByYear)
        {
            Console.WriteLine($"Year: {group.Year}, Orders: {group.OrderCount}");
        }
    }
    

    In this example:

    • GroupBy(o => o.OrderDate.Year) groups the orders by the year of the order.
    • The result is a list of years along with the number of orders placed in each year.

    8. Combining Multiple Queries

    Sometimes, you may need to combine multiple queries or filter data across multiple conditions. You can chain LINQ methods together to perform more complex queries.

    using (var context = new MyDbContext())
    {
        var customers = context.Customers
                               .Where(c => c.Name.StartsWith("J"))
                               .OrderBy(c => c.Name)
                               .Take(5)
                               .ToList();
    
        foreach (var customer in customers)
        {
            Console.WriteLine(customer.Name);
        }
    }
    

    In this example:

    • Where(c => c.Name.StartsWith("J")) filters customers whose names start with "J".
    • OrderBy(c => c.Name) sorts the customers by their name.
    • Take(5) limits the result to the first 5 customers.

    Summary

    Entity Framework allows you to query the data in your Entity Data Model using LINQ in a simple and intuitive way. You can:

    • Use LINQ queries to filter, sort, project, and join related data.
    • Leverage eager loading or lazy loading to control how related entities are loaded.
    • Perform aggregations and grouping operations to extract useful statistics.

    By understanding how to query entities effectively, you can build efficient and powerful data access layers for your applications.

    Previous topic 21
    Eager vs lazy loading, POCO classes, DBContext API
    Next topic 23
    Introduction to ASP.NET MVC

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,146
      Code examples0
      DifficultyIntermediate