作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个列表框,当我从这个名为 ListofKBrands1 的列表框中选择一个项目时,我收到此错误消息:
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
在代码隐藏中,此错误的位置:
if (co.Company != null)
我的代码:
private void ListofKBrands1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
RSPDbContext c = new RSPDbContext();
if (ListofKBrands1.SelectedItem != null)
{
ListBoxItem item = ListofKBrands1.SelectedItem as ListBoxItem;
KBrand co = item.Tag as KBrand;
if (ListofKBrands1.SelectedItem != null)
txtNewKBrand.Text = co.Name;
else
txtNewKBrand.Text = "";
int count = 0;
if (co.Company != null)
{
foreach (string a in cbCompany.Items)
{
if (a == co.Company.Name)
cbCompany.SelectedIndex = count;
count++;
}
}
else
cbCompany.SelectedIndex = 0;
}
}
错误前:
我的 KBrand.cs:
public class KBrand {
[Key]
public int Id { get; set; }
public String Name { get; set; }
public virtual Company Company { get; set; }
public override string ToString() {
return Name;
}
}
公司.cs:
public class Company
{
[Key]
public int Id { get; set; }
public String Name { get; set; }
public override string ToString() {
return Name;
}
}
如果选择的 KBrand 的公司为空,则不会出现此错误。但如果所选 KBrand 的公司不为空,我会收到此错误。我该如何解决此错误?提前致谢。
最佳答案
Company
在您的情况下应该是延迟加载的。但是您的实体现在处于分离状态(加载 KBrand
实体的上下文现在已被处置。因此,当您尝试访问 Company
属性时, Entity Framework 会尝试使用已处置的上下文来进行查询服务器。这给了你异常(exception)。
您需要将您的 KBrand
实体附加到当前上下文才能启用 lazy-loading
RSPDbContext c = new RSPDbContext();
KBrand co = item.Tag as KBrand;
c.KBrands.Attach(co);
// use co.Company
或者您需要使用 eager loading , 已加载 Company
。当你得到元素时是这样的:
RSPDbContext db = new RSPDbContext();
var brands = db.KBrands.Include(b => b.Company).ToList();
// assign brands to listbox
关于c# - 错误 :The ObjectContext instance has been disposed and can no longer be used for operations that require a connection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17693145/
我是一名优秀的程序员,十分优秀!