How to clear the DataContext cache on LinqToSql

When you get data using LinqToSql and change something in the object, you expect that calling get object again will invalidate the cache and return the new objects, but it doesn’t! LinqToSql will return a reference of the object, what means, it will return the same object you had before.

The code below force LinqToSql to get new object(s), not the one(s) it has in memory:

public Order Get(int id)
{
	var order = Context.Orders.SingleOrDefault(o => o.orderId == id);
	
	if (order != null)
		// invalidate cache
		Context.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, order);

	return order;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s