ModelValidationException是未处理的用户代码

你可以帮助我解决以下错误,我检查了所有没有ID错误

ModelValidationException未由用户代码处理

EntityFramework.dll中发生了’System.Data.Entity.ModelConfiguration.ModelValidationException’类型的exception,但未在用户代码中处理

附加信息:在模型生成期间检测到一个或多个validation错误:

public int GetCount() { ShoppingCartId = GetCartId(); // Get the count of each item in the cart and sum them up int? count = (from cartItems in _db.ShoppingCartItems where cartItems.CartId == ShoppingCartId select (int?)cartItems.Quantity).Sum(); // Return 0 if all entries are null return count ?? 0; } 

令人沮丧的.net并不总是向您展示内部exception。 使用此catch将代码包装在try块中

 catch (DbEntityValidationException ex) { // Retrieve the error messages as a list of strings. var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); // Join the list to a single string. var fullErrorMessage = string.Join("; ", errorMessages); // Combine the original exception message with the new one. var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); // Throw a new DbEntityValidationException with the improved exception message. throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); }