类型'System.ObjectDisposedException'的异常

时间:2012-07-25 11:17:07

标签: c# .net entity-framework ef-code-first

我有以下EF代码的第一个代码。它工作正常。但当我寻找'club2.Members'的价值时,它会说:

  

'club2.Members'抛出了'System.ObjectDisposedException'类型的异常。

消息是:

  

ObjectContext实例已被释放,不能再用于需要连接的操作。

我没有为Members属性设置值。没关系。但是它不应该在内部引起任何异常。

  1. 有没有办法克服这个异常?
  2. 删除此异常是否有助于提高性能?
  3. 为什么此异常不会导致程序执行终止?
  4. 注意:我不需要俱乐部实体中的会员数据(在我打电话的时候)。即使当时没有成员加入俱乐部。我只需要摆脱异常;不使用预先加载来加载数据。如何避免异常

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

2 个答案:

答案 0 :(得分:7)

您收到此错误是因为在执行查询后正在处理dbcontext。如果要使用“members”中的数据,请使用查询加载它: http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx

如果您不需要延迟加载,这意味着只加载您在查询中加载的数据(这将消除异常),请设置LazyLoadingEnabled = false。看这里: Disable lazy loading by default in Entity Framework 4

答案 1 :(得分:1)

APPROACH 1

不需要以下方法。这可以在目前的背景下完成。它只是一个选择。

GetClubs("club1");

APPROACH 2

附加实体解决了问题:

            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;

我不应该尝试引用club2.Members(俱乐部类),因为创建Person对象不需要它。

会员是俱乐部班级的相关数据。由于它是虚拟的,它将进行延迟加载。

在另一种情况下,如果我必须从不同的上下文中检索Members对象(这是一个相关数据),我应该依赖于预先加载(在为你提供Club对象的地方)。

请参阅以下内容:

  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