我有以下 EF 代码第一个代码。它工作正常。但是当我寻找“club2.Members”的价值时,它会说:
“club2.Members”引发了“System.ObjectDisposedException”类型的异常。
消息是:
ObjectContext 实例已被释放,不能再用于需要连接的操作。
我没有为 Members 属性设置值。没关系。但是,它不应该在内部引起任何异常。
- 有没有办法克服这个异常?
- 删除此异常是否有助于提高性能?
- 为什么这个异常没有导致程序执行终止?
注意:我不需要俱乐部实体中的会员数据(在我打电话的地方)。即使当时还没有会员加入俱乐部。我只需要摆脱异常;不要使用急切加载来加载数据。如何避免异常?
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
}
}