Adding constant where clasue is for Linq to SQL mapping

Is it possible to put a where where constant in a Linq to SQl mapping.

I really don't want to do this at the query level or in my data access object as they are completely generic nowadays and would like to keep it in a way that makes life for other developers and save me by repeating myself constantly.

Colin g

+1


source to share


2 answers


One way to solve this problem is to use an extension method that returns the IQueryable of your entity type, and then use it wherever that object is required.

For example, if all my custom queries were only interested in Horses that did not have the Inactive checkbox checked, I would have the GetHorses extension method:

public static IQueryable<Horse> GetHorses(this DataContext db)
{
    return from h in db.Horses
           where !h.Inactive
           select h;
}

      

Obviously, when the method returns IQueryable, you can do further filtering / ordering, etc. in any method that uses it. So instead of my custom requests it looks like this:



var deadHorses = from h in db.Horses
                 where !h.inactive && !h.Alive
                 select h;

      

they would look like this:

var deadHorses = from h in db.GetHorses()
                 where !h.Alive
                 select h;

      

+2


source


I believe you can do this using the Options property of your DataContext. Check out the AssociateWith method.



+1


source







All Articles