How to reuse the Select portion of a LINQ to SQL Query



TODO:

Have you ever wanted to reuse the select portion of a LINQ to SQL query.  For instance if you are selecting only a certain number of fields, you can reuse that code, so that you ensure it is common across the board.

 

SOLUTION:

Method:

 

public IQueryable<Customer> GetBaseCustomerData(MyDataContext currentContext, ref string ErrorMessage)
{
     try
     {
           return (
                    from c in currentContext.Customers
                    select new Customer
                    {
                        CustomerId = c.CustomerId,
                        CustomerFirstName = c.CustomerFirstName,
                        CustomerMI = c.CustomerMI,
                        CustomerLastName = c.CustomerLastName,
                    }
                );
     }
     catch (Exception ex)
     {
           ErrorMessage = ex.Message;
           return null;
     }
}

 

To Call:

 

To call:
var customers = (GetBaseCustomerData(base._Context, ref errorMsg)
                            .Where(cc => (cc.CustomerId == customerId)

 

 

NOTES:

customerId is a local variable for which I want to fetch data for.



Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading