简体   繁体   English

类型'System.ObjectDisposedException'的异常

[英]Exception of type 'System.ObjectDisposedException'

I have following EF code first code. 我有以下EF代码的第一个代码。 It is working fine. 它工作正常。 But when I look for the value of 'club2.Members', it says following: 但当我寻找'club2.Members'的价值时,它会说:

'club2.Members' threw an exception of type 'System.ObjectDisposedException'. 'club2.Members'抛出了'System.ObjectDisposedException'类型的异常。

Message is: 消息是:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. ObjectContext实例已被释放,不能再用于需要连接的操作。

I have not set value for Members property. 我没有为Members属性设置值。 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 ? 如何避免异常

在此输入图像描述

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

You're getting this error because you are disposing the dbcontext after you execute the query. 您收到此错误是因为在执行查询后正在处理dbcontext。 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 如果要使用“成员”中的数据,请使用查询加载它: http//blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature- CTP5部分-6加载相关-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. 如果您不需要延迟加载,这意味着只加载您在查询中加载的数据(这将消除异常),请设置LazyLoadingEnabled = false。 Look here: Disable lazy loading by default in Entity Framework 4 请在此处查看: 默认情况下,在Entity Framework 4中禁用延迟加载

APPROACH 1 方法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 方法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. 我不应该试图引用club2.Members(俱乐部类),因为创建Person对象不需要它。

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). 在不同的场景中,如果我必须从不同的上下文中检索Members对象(这是一个相关数据),我应该依赖于急切加载(在为您提供Club对象的位置)。

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 System.ObjectDisposedException:ObjectContext实例已被释放,不能再用于需要连接的操作

  3. The ObjectContext instance has been disposed and can no longer be used for operations that require a connection ObjectContext实例已被释放,不能再用于需要连接的操作

  4. ObjectContext instance has been disposed while binding 绑定时已释放ObjectContext实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM