0

在我自称的学习项目中,我确实偶然发现了一个奇怪的错误。

我有一堂课device

public class Device
{
    [Key]
    public int Id { get; set; }
    [MaxLength(50)]
    public String Name { get; set; }
    public Category Category { get; set; }
    /* .... */
}

和一堂课Category

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}

现在,如果我尝试直接在我的数据库中删除一个类别,操作将失败,因为外键约束仍然处于活动状态 - 这是好的和有意的。

然而,在我的 Mvc View 上,这个约束似乎没有激活。我可以删除每个类别,无论它是否仍在设备中使用。

这会导致设备没有类别。在我的控制器中调用 Edit 方法时,视图模型中填充了一个选择列表,其中包含每个类别和设备类别作为selected值。

var vm = new DeviceEditViewModel
{
    dev = device,
    CategoriesListItems = repo.GetCategories().Select(x => new SelectListItem
    {
        Value = x.ID.ToString(),
        Text = x.Name,
        Selected = x.Name == dev.Category.Name
    }),
    ManufactorListItems = repo.GetManufactors().Select(x => new SelectListItem
    {
         Value = x.ID.ToString(),
         Text = x.Name,
         Selected = x.Name == device.Manufactor.Name 
    })
};
return View(vm);

这段代码现在在调用没有类别的设备时会引发 NullReferenceException。

如何在我的类别删除操作中强制执行约束检查,如果数据不一致,如何防止编辑视图中的下拉列表分配选定的值?

至于约束检查,这是我迄今为止尝试过的,但确实不是工作。

//I still have to create a repository
public ActionResult DeleteConfirmed(int id)
{
    Category category = db.Categories.Find(id);
    int DevicesUsingCat = db.Devices.Include(o => o.Category)
                            .Where(d => d.Category.ID == id)
                            .Select(x => x).ToList().Count;
    if (DevicesUsingCat > 0)
    {
       ModelState.AddModelError("Usage", "The category is still in use and cannot be deleted.");
       return View(); //added. Now model error shows up.
    }
    db.Categories.Remove(category);
    db.SaveChanges();
    return RedirectToAction("Index");
}
4

0 回答 0