tags:

views:

430

answers:

1

When I make the same query twice, the second time it does not return new rows form the database (I guess it just uses the cache).

This is a Windows Form application, where I create the dataContext when the application starts.

How can I force Linq to SQL not to use the cache?

Here is a sample function where I have the problem:

public IEnumerable<Orders> NewOrders()
{
    return from order in dataContext.Orders
           where order.Status = 1
           select order; 
}
+5  A: 

The simplest way would be to use a new DataContext - given that most of what the context gives you is caching and identity management, it really sounds like you just want a new context. Why did you want to create just the one and then hold onto it?

By the way, for simple queries like yours it's more readable (IMO) to use "normal" C# with extension methods rather than query expressions:

public IEnumerable<Orders> NewOrders()
{
    return dataContext.Orders.Where(order => order.Status == 1);
}

EDIT: If you never want it to track changes, then set ObjectTrackingEnabled to false before you do anything. However, this will severely limit it's usefulness. You can't just flip the switch back and forward (having made queries between). Changing your design to avoid the singleton context would be much better, IMO.

Jon Skeet
It is at major refactoring for me to use another DataContext, because it is wrapped in a framework library.
Thomas Jespersen
Well, that's basically what you need to do. When faced with a bad design decision made earlier, I usually find it's *much* better to roll up your sleeves and fix it than to work around it, making it harder and harder to fix later.
Jon Skeet
Well... that is not an option.
Thomas Jespersen
I've just edited my answer with an alternative, but I still think it's almost certainly a mistake. LINQ to SQL was just not designed to be used the way you're using it.
Jon Skeet
sorry... that came out a little harsh. It just that the framwork is developed for web, an I have to make a litle WinForm admin program. If I have to refactor the entire library, I have days of work and days of testing. I just dog get why a query is cashed, without the option to force a requery.
Thomas Jespersen
Are you using a single DataContext all the way through your web application as well? I have no idea what the concurrency properties of DataContext are - imagine doing similar queries at the same time with the same context from different threads...
Jon Skeet
In web it is per request.
Thomas Jespersen
That is... it is stored in the HttpContext.Current.Items in case the request is swapped to another thread during a request.
Thomas Jespersen
Okay, that's not so worrying then :) Can't you hook into the same logic for your WinForms app? Give yourself some sort of "fake context" such that you'll get a new DataContext?
Jon Skeet