ModelValidationException 是未处理的用户代码

ModelValidationException was unhandled user code

你能帮我解决下面的错误吗,我检查了一切都没有 ID 错误

用户代码未处理 ModelValidationException

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

附加信息:在模型生成过程中检测到一个或多个验证错误:

 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 并不总是向您显示内部异常。用这个 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); }