tags:

views:

137

answers:

2

Is is possible to put a constant where clause to a Linq to SQl mapping.

I really don't want to do this at the query level or in my Data Access Object as these are currently completely generic and would like to keep it that way to make life for the other developers and save me repeating myself constantly.

Colin G

+2  A: 

One way I have tackled this is to use an extension method that returns an IQueryable of your entity type, and then use this wherever that entity is needed.

For example, if all my custom queries were only interested in Horses that didn't have the Inactive flag set, I would have an extension method called GetHorses:

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

Obviously as the method returns an IQueryable, you can do further filtering/ordering etc in any method that uses it. So instead of my custom queries looking 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;
Paul Nearney
+1  A: 

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

Rune Grimstad