0

I have an entity something like this:

public class Customer
{
    public string Id { get; set; }
    public string Name { get; set; }
}

I am reading using LinQ as follows:

public IQueryable<Customer> GetCustomer()
{
    var result = from cust in _dbContext.Customers.AsNoTracking() select cust;
    return result;
}

First time everything works just fine but when I added a customer in DB manually, the same customer is not reflecting in this query, it always returns the old records.

So how do I always get the updated customers from DB?

Note: I am using EF 4

vijay kumar
  • 273
  • 1
  • 3
  • 5

1 Answers1

0

The problem is the method call .AsNoTracking() The AsNotracking() method is a detached list of the data, verify on the link http://msdn.microsoft.com/en-us/data/hh949853.aspx in the 5.1 item explains this:

If you are in a read-only scenario and want to avoid the overhead of loading the objects into the ObjectStateManager, you can issue "No Tracking" queries. Change tracking can be disabled at the query level.

Note though that by disabling change tracking you are effectively turning off the object cache. When you query for an entity, we can't skip materialization by pulling the previously-materialized query results from the ObjectStateManager. If you are repeatedly querying for the same entities on the same context, you might actually see a performance benefit from enabling change tracking.

When querying using ObjectContext, ObjectQuery and ObjectSet instances will remember a MergeOption once it is set, and queries that are composed on them will inherit the effective MergeOption of the parent query. When using DbContext, tracking can be disabled by calling the AsNoTracking() modifier on the DbSet.

remove the .AsNoTracking() for the link query

Julio Borges
  • 630
  • 15
  • 28
  • even after removing .AsNoTracking() also its still reading the from cache and not reflecting the date in DB. – vijay kumar Aug 06 '13 at 14:05
  • I use the above code and it works well. This may depend on how you are entering data in context. When performing the insert you use _dbContext.Customers.Add (customer) .... or performs the insert via SQLComand? – Julio Borges Aug 06 '13 at 14:24
  • i have inserted the record manually in DB, so how do i refresh the context? – vijay kumar Aug 06 '13 at 14:29
  • In my context I use the `context.Configuration.AutoDetectChangesEnabled` with the value true. Check this. If not solve, check this answer: http://stackoverflow.com/questions/5799737/entity-framework-4-1-dbset-reload – Julio Borges Aug 06 '13 at 14:50
  • Hi, can you help me with this? I have to read the multiple columns using raw sql query var result = _dbContext.Database.SqlQuery("select ID, NAME, DB_FIELD from eis_hierarchy").ToList(); but not getting the output properly – vijay kumar Aug 07 '13 at 06:44