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

  • SEARCH
  • Home
  • 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 8343129
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T05:57:56+00:00 2026-06-09T05:57:56+00:00

I have following EF code first code. It is working fine. But when I

  • 0

I have following EF code first code. It is working fine. But when I look for the value of ‘club2.Members’, it says following:

‘club2.Members’ threw an exception of type ‘System.ObjectDisposedException’.

Message is:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

I have not set value for Members property. That’s okay. However it should not cause any exception internally.

  1. Is there a way to overcome this exception?
  2. Does removal of this exception help in improving performance?
  3. Why this exception did not cause termination of program execution?

Note: I don’t need the Members data in club entity (at the point where I have called). Even there is no members added to the club at that time. All i need is to get rid of the exception; not to load data using eager load. How to avoid the exception?

enter image description here

namespace LijosEF
{

public class Person
{
    public int PersonId { get; set; }
    public string PersonName { get; set; }
    public virtual ICollection<Club> Clubs { get; set; }
}

public class Club 
{
    public int ClubId { get; set; }
    public string ClubName { get; set; }
    public virtual ICollection<Person> Members { get; set; }

}




//System.Data.Entity.DbContext is from EntityFramework.dll
public class NerdDinners : System.Data.Entity.DbContext
{

    public NerdDinners(string connString): base(connString)
    { 

    }

    protected override void OnModelCreating(DbModelBuilder modelbuilder)
    {
         //Fluent API - Plural Removal
        modelbuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }

    public DbSet<Person> Persons { get; set; }
    public DbSet<Club> Clubs { get; set; }



}
}




    static void Main(string[] args)
    {
        Database.SetInitializer<NerdDinners>(new MyInitializer());

        CreateClubs();
        CreatePersons();

    }

    public static void CreateClubs()
    {

        string connectionstring = "Data Source=.;Initial Catalog=NerdDinners;Integrated Security=True;Connect Timeout=30";
        using (var db = new NerdDinners(connectionstring))
        {

            Club club1 = new Club();
            club1.ClubName = "club1";

            Club club2 = new Club();
            club2.ClubName = "club2";

            Club club3 = new Club();
            club3.ClubName = "club3";

            db.Clubs.Add(club1);
            db.Clubs.Add(club2);
            db.Clubs.Add(club3);

            int recordsAffected = db.SaveChanges();


        }
    }

    public static Club GetClubs(string clubName)
    {
        string connectionstring = "Data Source=.;Initial Catalog=NerdDinners;Integrated Security=True;Connect Timeout=30";
        using (var db = new NerdDinners(connectionstring))
        {

            var query = db.Clubs.SingleOrDefault(p => p.ClubName == clubName);
            return query;
        }
    }

    public static void CreatePersons()
    {
        string connectionstring = "Data Source=.;Initial Catalog=NerdDinners;Integrated Security=True;Connect Timeout=30";
        using (var db = new NerdDinners(connectionstring))
        {

            Club club1 = GetClubs("club1");
            Club club2 = GetClubs("club2");
            Club club3 = GetClubs("club3");

             //More code to be added (using db) to add person to context and save
        }
    }
  • 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-06-09T05:57:57+00:00Added an answer on June 9, 2026 at 5:57 am

    APPROACH 1

    There is no need for the following method. This can be done in the present context. It is only a select.

    GetClubs("club1");
    

    APPROACH 2

    Attaching the entities resolved the problem:

                Club club1 = GetClubs("club1");
                Club club2 = GetClubs("club2");
                Club club3 = GetClubs("club3");
    
                ((IObjectContextAdapter)db).ObjectContext.Attach((IEntityWithKey)club1);
                ((IObjectContextAdapter)db).ObjectContext.Attach((IEntityWithKey)club2);
                ((IObjectContextAdapter)db).ObjectContext.Attach((IEntityWithKey)club3);
    
    
                var test = club2.Members;
    

    I should not have tried to refer club2.Members (of Club class), since it is not needed for creating Person object.

    Members is related data in Club class. Since it is virtual, it will do lazy loading.

    In a different scenario, if I had to retrieve Members object (which is a related data) from a different context, I should rely on eager loading (in the place which provides you with Club object).

    Refer following also:

    1. Entity Framework: Duplicate Records in Many-to-Many relationship

    2. System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection

    3. The ObjectContext instance has been disposed and can no longer be used for operations that require a connection

    4. ObjectContext instance has been disposed while binding

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

Sidebar

Related Questions

I have the following code working fine but the problem is that it always
First up, sorry for the mega-posting of code but... I have the following DB
i am using the following password code http://www.zubrag.com/scripts/password-protect.php it is working fine but when
I have created this code in Jquery. And it is working fine but I
I have the following code: Public Shared Function GetAvailableManufacturers() As List(Of Manufacturer) 'first get
I'm using the Code First approach and have the following Model: public class Person
I have the following thread code which executes correct first time. After that from
I have the following C# code below. Object first = 5; Object second =
I have the following expression within a report: = Switch( Fields!RATE_CODE.Value = First, £/Week,
The following is using EF 5.0.0-rc and Code First. In my design, I have

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.