1

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.

4

1 回答 1

1

这里处理的是 DbContext 对象,它是 Controller 类中的一个实例变量。这在您发布的代码中不可见。MVC 脚手架代码生成器将它放在那里(连同 Dispose() 方法)。它的工作方式是,当请求进来时,控制器被创建,其中的方法运行,然后,控制器在请求结束时超出范围。如果您取出 Dispose() 方法,它仍然可以工作。但是,最好将它放在那里,因为它正在处理作为 IDisposable 的 DbContext 对象。使用本机资源(如数据库连接)的类实现 IDisposable。这意味着您应该在它们上显式调用 Dispose()。否则,数据库连接可能保持打开状态并导致连接池泄漏,直到垃圾收集器在某个未确定的时间完成对象。有关详细信息,请参阅 MSDN 文档中有关 IDispose 的文档。

于 2012-04-30T20:44:35.643 回答