Reputation: 245
In my controller I am creating a new subcategory object and saving it to my database like this:
[Authorize(Roles = "administrator")]
[HttpPost]
public ActionResult Create(CategoryViewModel viewmodel, HttpPostedFileBase Icon)
{
SubCategory subcategory = viewmodel.subcategory;
subcategory.Category = categorycontroller.getCategoryByName(viewmodel.SelectedValue);
if (Icon != null && Icon.ContentLength > 0)
{
// extract only the filename
var fileName = Path.GetFileName(Icon.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("../../Content/icons/"), fileName);
Icon.SaveAs(path);
subcategory.Icon = fileName;
}
if (ModelState.IsValid)
{
db.subcategories.Add(subcategory);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(subcategory);
}
After debugging the application I noticed that the controller correctly saves all my data including the reference to a category object in my newly created subcategory.
But the problem is when I load the data from my db later on the subcategory, object is missing its reference to my category object.
My viewmodel looks like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;
using SkyLearn.Areas.Categories.Controllers;
namespace SkyLearn.Areas.Categories.Models
{
public class CategoryViewModel
{
public List<SelectListItem> PossibleValues { get; set; }
public string SelectedValue { get; set; }
public SubCategory subcategory { get; set; }
public CategoryController categorycontroller;
public CategoryViewModel()
{
PossibleValues = new List<SelectListItem>();
}
}
}
And my method on the category controller that finds the object:
public Category getCategoryByName(string categoryname)
{
foreach (Category cat in getCategories())
{
if (cat.Title == categoryname)
{
return cat;
}
}
return null;
}
Why does my category object reference disappear guys? I'm in a blind.
Upvotes: 1
Views: 655
Reputation: 121
What's being disposed here is the DbContext object that's an instance variable in the Controller class. This isn't visible in your posted code. The MVC scaffolding code generator puts it there (along with the Dispose() method). The way it works is that when a request comes in, the Controller is created, the methods in it run, then, the Controller goes out of scope at the end of the request. It would still work if you took out the Dispose() method. However, it's good to have it in there because it is disposing the DbContext object which is an IDisposable. Classes that make use of native resources such as database connections implement IDisposable. This means that you should explicitly call Dispose() on them. Otherwise, the database connection could stay open and cause a connection pool leak until the garbage collector at some undetermined time finalizes the object. For more information, see the documentation on IDispose in the MSDN documentation.
Upvotes: 1