类型“System.ObjectDisposedException”的异常 [英] Exception of type 'System.ObjectDisposedException'

查看:2835
本文介绍了类型“System.ObjectDisposedException”的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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


'club2.Members'抛出了一个例外'System.ObjectDisposedException'。


消息是:


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


我还没有设置会员属性的价值。没关系。但是它不应该在内部引起任何异常。


  1. 有没有办法克服这个异常?

  2. 删除此异常是否有助于提高性能?

  3. 为什么这个异常不会导致程序执行的终止?

注意:我不需要会员实体的数据(在我打电话的地方)。即使当时没有会员加入俱乐部。所有我需要的是摆脱异常;不用加载负载来加载数据。如何避免例外



 命名空间LijosEF 
{

public class Person
{
public int PersonId {得到;组; }
public string PersonName {get;组; }
public virtual ICollection< Club>俱乐部{get;组; }
}

public class Club
{
public int ClubId {get;组; }
public string ClubName {get;组; }
public virtual ICollection< Person>会员{get;组; }

}




//System.Data.Entity.DbContext来自EntityFramework.dll
public class NerdDinners:System.Data.Entity.DbContext
{

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

}

protected override void OnModelCreating(DbModelBuilder modelbuilder)
{
//流畅的API - 多重删除
modelbuilder.Conventions.Remove< PluralizingTableNameConvention>();
}

public DbSet< Person>人{get;组; }
public DbSet< Club>俱乐部{get;组; }



}
}




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;
使用(var db = new NerdDinners(connectionstring))
{

俱乐部club1 = new Club();
club1.ClubName =club1;

俱乐部俱乐部2 =新俱乐部();
club2.ClubName =club2;

俱乐部俱乐部3 =新俱乐部();
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 = 。;初始目录= NerdDinners;集成安全= True;连接超时= 30;
使用(var db = new NerdDinners(connectionstring))
{

var query = db.Clubs.SingleOrDefault(p => p.ClubName == clubName);
返回查询;
}
}

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

俱乐部俱乐部1 = GetClubs(club1);
俱乐部俱乐部2 = GetClubs(club2);
俱乐部俱乐部3 = GetClubs(club3);

//要添加的代码(使用db)将人添加到上下文并保存
}
}


解决方案

方法1



不需要以下方法。这可以在当前的情况下完成。这只是一个选择。

  GetClubs(club1); 

方法2



附加实体解决了问题:

 俱乐部俱乐部1 = GetClubs(club1); 
俱乐部俱乐部2 = GetClubs(club2);
俱乐部俱乐部3 = 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对象(这是一个相关的数据),我应该依赖于渴望加载(在



另请参阅:


  1. 实体框架:多对多关系中的重复记录


  2. System.ObjectDisposedException:ObjectContext实例已被处理,不能再用于需要连接的操作。



  3. ObjectContext实例已被处理



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?

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

解决方案

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

这篇关于类型“System.ObjectDisposedException”的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆