0
我正在开发使用ASP.Net MVC 4框架的在线商店。实体框架不保存对象属性
我有一个对象类别 - 在存放物品的类别(男士服装 - 例如):
public class Category
{
[Required]
public long id { get; set; }
[Required]
public string name { get; set; }
public bool active { get; set; }
public bool displayOnTop { get; set; }
public bool showSubcategoriesItems { get; set; }
public Category parentCategory { get; set; }
public virtual Collection<Item> items { get; set; }
public Category()
{
this.items = new Collection<Item>();
}
}
有一个属性parentCategory - 这意味着这个类别包括到另一个(男士服装>例如衬衫)。
对于编辑现有的类别I使用了以下行动:
[HttpPost]
public ActionResult EditCategory(Category editedCategory, string parentCategorySelector)
{
UsersContext db = new UsersContext();
Category existingCategory = db.categories.SingleOrDefault(c => c.id == editedCategory.id);
long parentCategoryId = (long)Int32.Parse(parentCategorySelector);
Category parentCategory = db.categories.SingleOrDefault(c => c.id == parentCategoryId);
if (existingCategory == null) return RedirectToAction("Index", "Admin");
existingCategory.name = editedCategory.name;
existingCategory.active = editedCategory.active;
existingCategory.displayOnTop = editedCategory.displayOnTop;
existingCategory.showSubcategoriesItems = editedCategory.showSubcategoriesItems;
existingCategory.parentCategory = parentCategory;
db.Entry(existingCategory.parentCategory).State = EntityState.Modified;
db.SaveChanges();
return View(existingCategory);
}
一切工作正常,除非我想parentCategory设置为null - 它设置为NULL代码,但空值没有被保存到数据库 - 之前的值仍然存在。
但是,如果我不喜欢这样写道:
[HttpPost]
public ActionResult EditCategory(Category editedCategory, string parentCategorySelector)
{
UsersContext db = new UsersContext();
Category existingCategory = db.categories.SingleOrDefault(c => c.id == editedCategory.id);
long parentCategoryId = (long)Int32.Parse(parentCategorySelector);
Category parentCategory = db.categories.SingleOrDefault(c => c.id == parentCategoryId);
if (existingCategory == null) return RedirectToAction("Index", "Admin");
existingCategory.name = editedCategory.name;
existingCategory.active = editedCategory.active;
existingCategory.displayOnTop = editedCategory.displayOnTop;
existingCategory.showSubcategoriesItems = editedCategory.showSubcategoriesItems;
existingCategory.parentCategory = null;
db.Entry(existingCategory.parentCategory).State = EntityState.Modified;
db.SaveChanges();
return View(existingCategory);
}
即我将它设置为null无条件,它被正确保存。
我在做什么错?
非常感谢 - 它适用于我!的确Include语句接受字符串,而不是lambda:Include(“parentCategory”) –
很高兴帮助!接受lambda的包含在从EF 4.1开始的“System.Data.Entity”中。 –