Organizational Research By

Surprising Reserch Topic

Entity Framework Caching Issue

I am new to Entity Framework.

I have get to some values in my database using EF. It returns perfectly, and the values are shown in labels. But When I delete all values in my table (without using EF), the EF query is returning my old values. I know the EF stores the values in cache and returns the cached data for subsequent runs. Is this correct?

So how can I solve the problem when I have deleted all values in my database, but EF returns the old values?


Now i used datamodel.SaveChanges(); .But now it's return same old values.

My sample query is look like below:

SchoolBriefcaseEntities datamodel = new SchoolBriefcaseEntities();
            List compliance=new List();
            IList complianceModel;
            if (HttpContext.Current.User.IsInRole("SuperAdmin"))
                compliance = datamodel.Compliances.Where(c => c.School.DistrictId == districtId).ToList();

asked May 16, 2015 in Csharpenet by rajesh
0 votes

Related Hot Questions

2 Answers

0 votes
I recommend you to use some MergeOption to all EntitieSet after create the context, like this:

var objSetProps = ctx.GetType().GetProperties().Where(prop => prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(ObjectSet<>));
foreach (PropertyInfo objSetProp in objSetProps)
    ObjectQuery objSet = (ObjectQuery)objSetProp.GetValue(ctx, BindingFlags.GetProperty, null, null, null);
    objSet.MergeOption = MergeOption.PreserveChanges;
Read about the MergeOption here: Your will use NoTracking, I think.

But, iy you whant CLEAR the "cached" entities, detaching it.

var entidades = Ctx.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified | EntityState.Unchanged);
foreach (var objectStateEntry in entidades)
Where Ctx are my Context.
answered May 16, 2015 by rajesh
0 votes
EF will not load changes unless you re query the context. EF queries db and loads maps them into objects, it watches changes you perform on objects and not on the database. EF does not track changes made directly to database and it will never track.

You have loaded a List, that List is your cache in memory. Even calling Save Changes will not refresh. You will have to query the context once again, that is create new list.

To see changes You will have to execute following line once more,

datamodel.Compliances.Where(c => c.School.DistrictId == districtId).ToList()
answered May 16, 2015 by rajesh