Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6651119
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T00:58:21+00:00 2026-05-26T00:58:21+00:00

I already checked this using a memory profiler and there are no real entities

  • 0

I already checked this using a memory profiler and there are no real entities which stay in memory but hash-sets, dictionaries and EntityKey objects — but I found no way how to disconnect these references.

So simple question: How do I stop the context (or its ObjectStateManager) from growing infinitely in size?

[And yes, I know that long living contexts should be avoided, but in this case it’s one complex analysis run which needs several hierarchical data being loaded (and the sample below is just a minimal problem demonstration) so finally it is a “short” living one-operation context.]

Steps to repro:

  • create a new console application
  • create a EF model for a Northwind database (either use some real SQL Server or copy Northwind.sdf from Compact Samples folder)
  • use code below:

Code [Updated, doesn’t need real DB connection anymore]:

class Program
{
    static void Main()
    {
        const double MiB = 1024 * 1024;
        using ( var context = new NorthwindEntities() )
        {
            var last = GC.GetTotalMemory(true) / MiB;
            Console.WriteLine("before run: {0:n3} MiB", last);
            var id = 0;
            while ( true )
            {
                Run(context, ref id);

                GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
                GC.WaitForPendingFinalizers();
                var current = GC.GetTotalMemory(true) / MiB;
                Console.WriteLine("after run: {0:n3} MiB (+{1:n3} MiB)", current, current - last);
                last = current;

                if ( Console.KeyAvailable )
                    break;
                Console.WriteLine(new string('-', 100));
            }
        }
    }

    static void Run(NorthwindEntities context, ref int id)
    {
        for ( int i = 0; i < 100000; i++ )
        {
            var category = new Category { Category_ID = ++id };
            category.EntityKey = new EntityKey("NorthwindEntities.Categories", "Category_ID", id);
            var product = new Product { Product_ID = id, Category_ID = id };
            product.EntityKey = new EntityKey("NorthwindEntities.Products", "Product_ID", id);
            product.Category = category;
            context.Attach(product);
            context.Detach(product);
            context.Detach(category);
        }

        var ctr = 0;
        Console.WriteLine("Enumerating living/attached objects:");
        const EntityState AllStates = EntityState.Added | EntityState.Deleted | EntityState.Modified | EntityState.Unchanged;
        foreach ( var entry in context.ObjectStateManager.GetObjectStateEntries(AllStates) )
            Console.WriteLine("  #{0} [{1}] {2}", ++ctr, entry.EntityKey, entry.Entity);
        if ( ctr == 0 )
            Console.WriteLine("  NOTHING (as expected)");
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T00:58:22+00:00Added an answer on May 26, 2026 at 12:58 am

    Since I’m only detaching entities directly after having called SaveChanges(), I’m now counting the number of detached entities and when the counter reaches 10,000 I detach all still living (and needed) objects from the context and create a new context to which I attach all detached objects.
    Downside: The IsLoaded property of EntityReferences and EntityCollections is now always false (but I don’t rely on this).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Already checked exisitng questions for this, but didn't find an exact match. My aim
I've already checked this.. similar question but I am not convinced about the answers...
I already asked this question at the JOS-.NET board but Joel is closing that
I've already checked out the question Deleting duplicate records using a temporary table and
I have this piece of Javascript and it just won't work. I allready checked
Already finished implementing the player. I want to implement the progress bar. But I
I already know how to: Load properties files into my Spring configuration using: <context:property-placeholder
I already know the obvious answer to this question: just download <insert favorite windows
Here is my setup: If radiobutton1 is already checked when the page loads (it
I know this has been asked plenty of times before and I already went

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.