1

我有可以有子类别/根类别的类别。当我将根类别更改为其他类别时,它可以工作,但是当我尝试将其设置为null(使其成为根类别)时,它不会改变任何东西。如果这有什么不同,我将使用代码优先的方法。

这是我明确声明category.RootCategory = null但它不起作用的代码,根类别仍然是之前设置的。

控制器

[HttpPost]
public ActionResult Edit(Category c, int? rootCategoryID)
{
    var category = _db.Categories.Where(x => x.ID == c.ID).Single();

    if (TryUpdateModel(category))
    {
        cateogry.RootCategory = null;
            _db.SaveChanges();
        return Content(Infrastructure.Helpers.SerializeObject(category));
    }

    return Redirect("/admin/category");
}

模型

public class Category
{
    public int ID { get; set; }
    virtual public Category RootCategory { get; set; }
    virtual public ICollection<Category> ChildCategories { get; set; }
}

更新

非常奇怪的行为。当我调试它并一步一步慢慢地更新它时,当我不调试它或快速运行时它不会更新。我不知道为什么会这样。

4

1 回答 1

1

无论如何,我添加public int? RootCategoryID { get; set; }到我的模型中,现在我可以像这样编辑它。

[HttpPost]
public ActionResult Edit(Category c)
{
    var cateogry = _db.Categories.Where(x => x.ID == c.ID).Single();

    if (TryUpdateModel(cateogry))
    {
        cateogry.UpdatedDateTime = DateTime.Now;
        _db.SaveChanges();
    }

    return Redirect("/admin/category");
}

它现在可以工作,但仍然不知道为什么它在运行时没有 RootCategoryID 并在调试时工作。

于 2012-10-01T15:44:53.343 回答