HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Performance optimization for Linq To SQL

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
linqsqloptimizationforperformance

Problem

I have been working with C# for quite some time but relatively new to the concepts of lambdas and Linq. I was working with a Linq To SQL example and trying to write a generic solution for executing a search against a collection of entities (eg. list of Customer objects) where the search parameter will be specified by passing a partially filled object of the entity class itself. I was doing this just to ensure that a person does not have to go on specifying different overloads for different searches based on the entity class attributes and trying to write a generic solution which will cater to any entity class.

Hence I used reflection and an array of predicates to successively apply the Where clauses to the collection.

Client App

using (CustomerManager oCustomerManager = new CustomerManager())
{
   IEnumerable customers = oCustomerManager.Load();

   Customer oSearchCustomer = new Customer();
   oSearchCustomer.City = "London";
   oSearchCustomer.ContactName = "Thomas Hardy";

   IEnumerable customerList = oCustomerManager.Search(oSearchCustomer);

   foreach (Customer customer in customerList)
   {
      Console.WriteLine(customer.ToString());
   }
}


Manager Class

public IEnumerable Search(Customer searchObject)
{
    IEnumerable customers = DataContext.Customers;
    List> result = 

    DataContext.Customers.GenerateFilterClause(searchObject);

    foreach (var item in result)
    {
        customers = customers.Where(item);
    }

    return customers;
 }


Extension Method Utility Class

```
public static class UtilityExtensions
{
public static List> GenerateFilterClause(this IEnumerable
collection, T searchEntity)
{
List> whereFilterList = new List>();
Func predicate = null;

var propertyList = searchEntity.GetType().GetProperties();

foreach (PropertyInfo p in propertyList)
{
if (p.GetCustomAttributes(false).OfType().Count() > 0)
{
string prop

Solution

How much did you look into LINQ to SQL? Unless you have a reason not to expose the DataContext, you can just perform queries on it without using the 'search object'.

from c in DataContext.Customers
where c.City == "London" && c.ContactName == "Thomas Hardy"
select c


I haven't used LINQ to SQL myself yet, so I can't really tell much about the best practices and whether or not exposing DataContext is a good idea. Probably it's best to use an existing ORM framework. DataObjects.NET looks really nice.

A nice ORM overview can be found on ORMbattle.

Code Snippets

from c in DataContext.Customers
where c.City == "London" && c.ContactName == "Thomas Hardy"
select c

Context

StackExchange Code Review Q#2154, answer score: 3

Revisions (0)

No revisions yet.