Search code examples
c#asp.netentity-frameworkenterprise-library

How to save EF in a cache layer?


I'm using Entity Framework.

I save the object in an MS_library cache manager.

However I now encounter a problem: when I retreieve this object from the cache

its ContextObj is already disposed.

How can I fix this without mapping each entity to my model object?

public partial class MaMDBEntities : DbContext
{
    public MaMDBEntities()
        : base("name=MaMDBEntities")
    {

        ObjectContext.
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public DbSet<App> Apps { get; set; }
    public DbSet<AppsData> AppsDatas { get; set; }
    public DbSet<Browser> Browsers { get; set; }
    public DbSet<BrowserVersion> BrowserVersions { get; set; }
    public DbSet<BrowserVerToCriteria> BrowserVerToCriterias { get; set; }
    public DbSet<CommonConfig> CommonConfigs { get; set; }
    public DbSet<Country> Countries { get; set; }
    public DbSet<Criterion> Criteria { get; set; }
    public DbSet<CTID> CTIDS { get; set; }
    public DbSet<DatabaseLastUpdate> DatabaseLastUpdates { get; set; }
    public DbSet<Group> Groups { get; set; }
    public DbSet<MamConfiguration> MamConfigurations { get; set; }
    public DbSet<MamConfigurationCTID> MamConfigurationCTIDs { get; set; }
    public DbSet<MamConfigurationStatus> MamConfigurationStatuses { get; set; }
    public DbSet<Pair> Pairs { get; set; }
    public DbSet<SettingsServicesConfig> SettingsServicesConfigs { get; set; }
    public DbSet<sysdiagram> sysdiagrams { get; set; }
    public DbSet<CtidPgPastExistence> CtidPgPastExistences { get; set; }

    public virtual ObjectResult<usp_AppsData_GetAll_Result> usp_AppsData_GetAll()
    {
        return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<usp_AppsData_GetAll_Result>("usp_AppsData_GetAll");
    }
}

Solution

  • Either load the navigational properties that you try to access with include() or turn off the ProxyObjectCreation in the object context properties.

    Context.SomeCollection.Include("NavigationalProperty")
    

    or

    Context.Configuration.ProxyCreationEnabled = false;
    

    If you decide to turn off the proxy creation you must retest all of your queries that are using lazy loading, because there will be silent bugs introduced in your solution.