Question

I am new at Entity Framework Code first and I am building a small app to get used to it.When the site runs for the first time I access existing catalog values inside the database and display this in a drop down using razor.

public void GetCats()
    {
        using (context = new RecipeContext())
        {
            try
            {
                var query = (from r in context.Catalogues
                             select r).Distinct().ToList();

                catalogues = query.Select(t => t.CatalogueName.ToString()).ToList();
                catalogues.Sort();


            }
            catch (Exception exe)
            {
                labMessage = exe.Message;

            }

        }
    }

Now when I try to add Catalogue values to the context I get the above error.

public void AddCatalogue(string catalogueName)
    {

        using(context = new RecipeContext())
        {
            try
            {
                catalogueName = catalogueName.ToLower();
                var catalogue = new RecipeCatalogue { CatalogueName = catalogueName };

                if (context.Catalogues.Where(t => t.CatalogueName == catalogueName).Count() > 0)
                {
                    labMessage = "The value already exists";
                    CatalogueNameAdded = false;
                    return;

                }
                context.Catalogues.Add(catalogue);
                context.SaveChanges();
                catalogueNameAdded = true;
                labMessage = "a new catalogue record was added";


            }
            catch (Exception exe)
            {
                catalogueNameAdded = false;
                labMessage = exe.Message;
            }

        }
    }

The values are being added to the database however but still get the above exception.

Advice perhaps as to why I get this error. This is my Controller method which calls the above method.

[HttpPost]
    public JsonResult AddNewCatalogue(string catalogueName)
    {
        ViewModel model = new ViewModel();
        model.AddCatalogue(catalogueName);
        return Json(new { ViewModel = model });

    }
Was it helpful?

Solution

Is context a field in your model? I think you shouldn't assign to a field in a using statement. At the closing brace of the using context will be disposed. If you access that field in another place (without re-assigning) you are accessing a disposed object that might raise the exception you are getting.

Try changing your using statetments like this using (var context = new RecipeContext()). (note var before context) and drop the field.

OTHER TIPS

Your context is being disposed when the using block where you're performing your query is exited. That's the whole point of the using statement:

using(context = new RecipeContext()) {
    // ...
}
// context has been disposed at this point

Instead of a using statement, give your class a field to hold a reference to it.

private RecipeContext _context;

public void GetCats() {
    _context = new RecipeContext();
    // ...
}

public void AddCatalogue(string catalogueName) {
    // Use _context here
}

Just make sure that at some point, you call _context.Dispose(). Also, it's probably better to create the context in the constructor or someplace else that's only called once, prior to performing any operations with it.

Just my 2 cents:

The above answers are correct! If you're using some pattern like a repository, I sugest to implement it as a singleton! This way your objects will not be detached, and you're context will not be disposed!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top