3

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
        }
    }
LCJ
  • 22,196
  • 67
  • 260
  • 418
  • I just overlooked on your code. Why do you create another db instance in CheckValues? – Amiram Korach Jul 26 '12 at 07:35
  • @AmiramKorach I have another method - CreatePersons. I will have to use a new context there. I am using Context Per Request approach. Persons need to know about the Clubs. – LCJ Jul 26 '12 at 08:05
  • This code doesn't make sense. You're not using the db variable in CreatePersons at all. Each GetClubs call is using its own db variable. – Amiram Korach Jul 26 '12 at 08:12
  • @AmiramKorach. More code will be added in CreatePersosns method (using db) to add person to context and save – LCJ Jul 26 '12 at 09:08
  • OK. Just make sure you're not connecting between entities from different contexts. – Amiram Korach Jul 26 '12 at 09:13
  • Please try add `var query = db.Clubs.SingleOrDefault(p => p.ClubName == clubName); /* try this...*/ if (query.Members == null) {} return query;` and see what happens... – Jitka Darbie Hübnerová Feb 11 '15 at 17:51

2 Answers2

9

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

Community
  • 1
  • 1
Amiram Korach
  • 13,056
  • 3
  • 28
  • 30
  • 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 also, at that point. All i need is to get rid of the exception; not to load data. How to avoid the exception? – LCJ Jul 25 '12 at 14:39
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

Community
  • 1
  • 1
LCJ
  • 22,196
  • 67
  • 260
  • 418
  • @AmiramKorach What do you think about this approach? – LCJ Jul 26 '12 at 06:34
  • 1
    Stick with Amiram's suggestion. This only works because you're reattaching the entities to a new context. I think in your case, you want to use Include for eager loading. Opening up new contexts each time you want to access a navigation property is not a good idea. Remember, because you marked your navigation properties as virtual, EF is going to return a dynamic proxy which won't work when the context is disposed. Returning all the data you need before you close the context will solve the issue. – JaySilk84 Jul 26 '12 at 07:29
  • I think this is dangerous. As I commented above, I don't think there is a need to open a new context in CheckValues at all. Also I wouldn't try to attach entities to more than one context. I'm not sure you're not going to get an exception for that. – Amiram Korach Jul 26 '12 at 07:38
  • @JaySilk84 I think, eager loading is for retrieving related data. In my scenario, I am not retrieving related data - I am just setting related data (Club is related data for person). I don't think, eager loading is needed. What do you think? – LCJ Jul 26 '12 at 09:06
  • 1
    @Lijo If you don't need the data, then don't access the navigation property. In your case above, you only got the exception in the debugger when you tried to expand the `Members` property. That exception won't be thrown at run time if you never access the property. If you're never going to need to see all the members in a club (`Club.Members`) but just need the clubs a person belongs to (`Person.Clubs`) then just remove the `Members` nav property off of `Club`. You don't need to map all properties or relationships in your models. – JaySilk84 Jul 26 '12 at 13:58
  • @JaySilk84 Thanks. That make sense. Please see my updated answer. Also, I have another EF question http://stackoverflow.com/questions/11632951/primary-key-violation-inheritance-using-ef-code-first. – LCJ Jul 26 '12 at 14:00