c# - 错误 :The ObjectContext instance has been disposed and can no longer be used for operations that require a connection

标签 c# wpf entity-framework

我有一个列表框,当我从这个名为 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;
        }
    }

错误前:

enter image description here

我的 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/

相关文章:

c# - Entity Framework 代码优先 : CASCADE DELETE for same table many-to-many relationship

c# - 什么是 EF 重写规则?

c# - Entity Framework 错误地跨多个列强制执行唯一约束

C# 泛型 : How can I use them generically?

c# - 运算符 >= 不能应用于字符串和日期时间类型的操作数

在 XP 上使用多播的 C# SocketException

wpf - ProgressBar 不更新通过绑定(bind)更改为 Maximum

C# 通过 IEEE 754 从 float 转换为 hexstring 并返回 float

.net - 重新创建上下文时,wpf mvvm datagrid丢失排序

wpf - 两种方式 wpf datagrid 绑定(bind)到数据库