Exception of type 'System.ObjectDisposedException'

31,016

Solution 1

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

Solution 2

You're getting this error because you are disposing the dbcontext after you execute the query. If you want to use the data in "members" then load it with the query: http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx

If you don't need lazy loading, which means that only data you're loading in the query is loaded (this will eliminate the exception), set LazyLoadingEnabled = false. Look here: Disable lazy loading by default in Entity Framework 4

Share:
31,016
LCJ
Author by

LCJ

.Net / C#/ SQL Server Developer Some of my posts listed below -- http://stackoverflow.com/questions/3618380/log4net-does-not-write-the-log-file/14682889#14682889 http://stackoverflow.com/questions/11549943/datetime-field-overflow-with-ibm-data-server-client-v9-7fp5/14215249#14215249 http://stackoverflow.com/questions/12420314/one-wcf-service-two-clients-one-client-does-not-work/12425653#12425653 http://stackoverflow.com/questions/18014392/select-sql-server-database-size/25452709#25452709 http://stackoverflow.com/questions/22589245/difference-between-mvc-5-project-and-web-api-project/25036611#25036611 http://stackoverflow.com/questions/4511346/wsdl-whats-the-difference-between-binding-and-porttype/15408410#15408410 http://stackoverflow.com/questions/7530725/unrecognized-attribute-targetframework-note-that-attribute-names-are-case-sen/18351068#18351068 http://stackoverflow.com/questions/9470013/do-not-use-abstract-base-class-in-design-but-in-modeling-analysis http://stackoverflow.com/questions/11578374/entity-framework-4-0-how-to-see-sql-statements-for-savechanges-method http://stackoverflow.com/questions/14486733/how-to-check-whether-postback-caused-by-a-dynamic-link-button

Updated on March 06, 2020

Comments

  • LCJ
    LCJ about 4 years

    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
            }
        }