views:

729

answers:

3

Is there a way to ensure a particular conditional clause is added to the expression tree on each select from a particular table?

For example, a table with a field with the date a record was deleted should never come back or be included in any kind of statement.

Rather than include a where clause each time, is there a way, without creating a view, to add a conditional to each select?

--- Edit for clarity below ---

I'm looking for a function I can partial, much like the Insert/Update/Delete functions, but for Selecting. I want to apply a blanket filter to all queries against a table.

Furthermore, if I get a collection of items from a parent, I want that set to be filtered as well.

Something like:

Private Function BaseItems() As IQueryable(Of Item)
    Return (From mi In dataContext.Items Where mi.DeletedAt Is Nothing Select mi)
End Function
Public Function GetItems() as list(of Item)
    Return (From mi in BaseItems() select mi).ToList()
End Function

works for functions I write and call. ITEMS, can be a child of MASTER, for example.

'assume TheMaster is a LinqToSQL data class which has a one to many child of Items
TheMaster.Items.Count '<-- will bring back all Items.

How do I always filter what populates by data classes?

A: 

I'm not sure I understand the context of your question. However you can add more where conditionals on a linq query. If you return an IQueryable, you'll only return a runnable query and you can chain on it other LINQ queries. Afaik it won't execute until you start making it to an IEnumerable or List to iterate through.

Example on LINQ-to-SQL:

MyDataContext context = new MyDataContext();

public IQueryable<MyTable> GetTable() {
    return from record in context.Records
           where record.Date > DateTime.Now
           select record;
}

public IEnumerable<MyTable> GetTableWithinWeek() {
    return from record in GetTable()
           where record.Date < DateTime.Now.AddDays(7);
           select record;
}

I hope my answer makes sense.

Spoike
Yes, your answer makes sense and is a possible solution; however, that would still require me to start my queries from another function. I'm more or less looking for a way to do this without rewriting too much code -- looking for an existing function to tap in to.
JazzHands
JazzHands: You could try to write your own extension method against the DataContext if you want to do it with less code.
Spoike
+1  A: 

You should be able to do this my putting the items into a list and then use lambda expressions to filter the list?

MyListObject.Where(x => x == x.Date);
Frost
A: 

AssociateWith in the DataLoadOptions of the DataContext seems to do what I'm needing.

JazzHands