Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error:The ObjectContext instance has been disposed and can no longer be used for operations that require a connection

i have a listbox and when i select an item from this listbox called as ListofKBrands1, i take this error message:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

In code-behind,place of this error:

if (co.Company != null)

my code:

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

before error:

enter image description here

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

company.cs:

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

    public override string ToString() {
        return Name;
    }
}

if company of selected KBrand is null, this error does not appear. but if company of selected KBrand is not null, i take this error.how can i fix this error ? thanks in advance.

like image 347
rockenpeace Avatar asked Jul 17 '13 06:07

rockenpeace


1 Answers

Company should be lazy-loaded in your case. But your entity now in detached state (context which loaded KBrand entity now disposed. So, when you are trying to access Company property, Entity Framework tries to use disposed context to make query to server. That gives you exception.

You need to attach your KBrand entity to current context in order to enable lazy-loading

RSPDbContext c = new RSPDbContext();
KBrand co = item.Tag as KBrand;
c.KBrands.Attach(co);
// use co.Company

OR you need to use eager loading, to have Company already loaded. Something like this when you getting items:

RSPDbContext db = new RSPDbContext();
var brands = db.KBrands.Include(b => b.Company).ToList();
// assign brands to listbox
like image 106
Sergey Berezovskiy Avatar answered Sep 28 '22 07:09

Sergey Berezovskiy