0

Possible Duplicate:
DbContext's internal caching (?)

I have an instance of my DbContext and a IQueryable in the ViewModelBase which fills from BootStrapper and the IQueryable needs to reload from the database several times, and I want to do it by calling some simple method without caring about what the query expression is.

In simple words :

I'd like to load the data into an IQueryable<T> without rewriting the expression and tools I have are:

1 => An IQueryable

2 => An instance of DbContext

As I change data in the database and try IQueryable.ToList() , the result does not update.

IQueryable<Person> ViewModelDataContext;
ViewModelDataContext = repository.GetAll<Person>();
var x = ViewModelDataContext.ToList();
//Some changes into database
repository = new Repository();
var y = ViewModelDataContext.ToList();
//But as result, the x is exactly returns the same result as y and I'd like the y to be updated after  database changes.

Any suggestions?

Community
  • 1
  • 1
Mohsen
  • 4,000
  • 8
  • 42
  • 73
  • When you call `ToList` on the `IQueryable` it'll load the data every time. `IQueryable` does not retain data it represents a query. – Eranga Aug 12 '12 at 07:14
  • You will have to show some code. – Ladislav Mrnka Aug 12 '12 at 07:47
  • 1
    DbContext API does not allow you to change the `MergeOption` to `OverwriteChanges`. Check [this answer](http://stackoverflow.com/a/7099364/60108) for possible workaround. – Eranga Aug 12 '12 at 07:51
  • @Ladislav Mrnka:just added some code – Mohsen Aug 12 '12 at 07:58
  • You must analyze why it doesn't work. We don't see whole your application and problem description "it doesn't work" will not lead to the answer. The approach in the linked question is correct and it works. – Ladislav Mrnka Aug 12 '12 at 08:11
  • I think maybe [this](http://msmvps.com/blogs/kevinmcneish/archive/2010/02/16/setting-entity-framework-mergeoptions-what-works-what-doesn-t.aspx) can solve the problem what do you think? – Mohsen Aug 12 '12 at 08:16
  • @Ladislav Mrnka:I mean the first answer, thank you Ladislav Mrnka. – Mohsen Aug 12 '12 at 08:24
  • @Ladislav Mrnka: Can I refresh IQueriable from database after repository = new Repository(); without rewriting the query?(without rewriting ViewModelDataContext = repository.GetAll();) – Mohsen Aug 12 '12 at 11:42

1 Answers1

1

Most likely, the problem is that Entity Framework returns you (rightfully) the same entity instances every time. This is an important feature of an ORM. It does not without your permission overwrite their fields with fresh values from the database. If it did it would lead to spurious state corruption and non-local side-effects across your application.

If you were to load a non-entity type using this approach it would work. Or read about merge options.

usr
  • 168,620
  • 35
  • 240
  • 369
  • Thank you but now my problem is the IQueriable, why it does not upudate after I made a new instance of dbContext? – Mohsen Aug 12 '12 at 11:32