' System.Data.Entity.ModelConfiguration.ModelValidationException'发生在EntityFramework.dll中

时间:2017-10-29 19:08:11

标签: c# asp.net asp.net-mvc entity-framework exception-handling

我是asp.net的新手并且不太了解。我正在做一个项目。当我尝试创建一个新类别时。我面临例外。

' System.Data.Entity.ModelConfiguration.ModelValidationException'发生在EntityFramework.dll中但未在代码中处理。

这是我的行动方法。

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,Name")] Category category)
    {

        if (ModelState.IsValid)
        {
            db.Categories.Add(category);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(category);
    }

这是类别类

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

    [Display(Name = "Category")]
    [Required(ErrorMessage = "Category name is required")]
    [MaxLength(45, ErrorMessage = "The category name can be maximum 45 characters long")]
    public string Name { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

这是DbContext

 public class DbClass : DbContext
{
    public DbClass()
        : base("DefaultConnection")
    {
        Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbClass>());
    }

    public DbSet<Category> Categories { get; set; }

    public DbSet<Customer> Customers { get; set; }

    public DbSet<Product> Products { get; set; }

我无法理解为什么会出现此异常以及如何解决这个问题。请帮忙。感谢。

1 个答案:

答案 0 :(得分:0)

尝试在try catch块中包装您的代码段。

try
{
    if (ModelState.IsValid)
    {

        db.Categories.Add(category);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
}
catch (Exception /* ex */)
{
    //Log the error (uncomment ex and place a break point on the line below to check the inner exception.  Ideally log the error so it can be reviewed.)
    ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}