错误:ObjectContext实例已被释放,不能再用于需要连接的操作

roc*_*ace 5 c# wpf entity-framework

我有一个列表框,当我从这个列表框中选择一个名为ListofKBrands1的项目时,我会收到以下错误消息:

ObjectContext实例已被释放,不能再用于需要连接的操作.

在代码隐藏中,出现此错误:

if (co.Company != null)
Run Code Online (Sandbox Code Playgroud)

我的代码:

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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

错误之前:

在此输入图像描述

我的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

company.cs:

public class Company
{
    [Key]
    public int Id { get; set; }
    public String Name { get; set; }

    public override string ToString() {
        return Name;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果所选KBrand的公司为null,则不会出现此错误.但如果所选KBrand的公司不为null,我会接受此错误.我可以修复此错误吗?提前致谢.

Ser*_*kiy 19

Company在你的情况下应该是懒惰的.但是你的实体现在处于分离状态(加载KBrand实体的上下文现在被处理掉了.因此,当你试图访问Company属性时,实体框架会尝试使用已处置的上下文来对服务器进行查询.这会给你带来异常.

您需要将KBrand实体附加到当前上下文以启用延迟加载

RSPDbContext c = new RSPDbContext();
KBrand co = item.Tag as KBrand;
c.KBrands.Attach(co);
// use co.Company
Run Code Online (Sandbox Code Playgroud)

或者您需要使用预先加载,Company已经加载.当你得到物品时,这样的东西:

RSPDbContext db = new RSPDbContext();
var brands = db.KBrands.Include(b => b.Company).ToList();
// assign brands to listbox
Run Code Online (Sandbox Code Playgroud)