ModelValidationException是未处理的用户code [英] ModelValidationException was unhandled user code
问题描述
您可以帮我下面的错误,我检查一切没有ID错误
ModelValidationException被取消用户code处理
类型'System.Data.Entity.ModelConfiguration.ModelValidationException的异常出现在EntityFramework.dll但在用户code没有处理
更多信息:模型生成过程中检测到一个或多个验证错误:
公众诠释getCount将()
{
ShoppingCartId = GetCartId(); //获取在车中的每个项目的数量和总结起来
诠释?计数=(从_db.ShoppingCartItems cartItems
其中,cartItems.CartId == ShoppingCartId
选择(INT?)cartItems.Quantity).SUM();
//返回0,如果所有的项目都为空
返回计数? 0;
}
无奈的是.NET并不总是告诉你内部异常。这种抓你的包裹code try块
赶上(DbEntityValidationException前){
//检索错误消息作为字符串列表。
VAR errorMessages = ex.EntityValidationErrors
.SelectMany(X => x.ValidationErrors)
。选择(X => x.ErrorMessage); //加入列表,一个字符串。
变种fullErrorMessage =的string.join(;,errorMessages); //用新合并原来的异常消息。
VAR exceptionMessage = string.Concat(ex.Message,验证错误是:fullErrorMessage); //抛出一个新的DbEntityValidationException与改进的异常信息。
抛出新DbEntityValidationException(exceptionMessage,ex.EntityValidationErrors); }
Can you help me on the following error, i checked everything no ID mistakes
ModelValidationException was un handled by user code
An exception of type 'System.Data.Entity.ModelConfiguration.ModelValidationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: One or more validation errors were detected during model generation:
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;
}
Frustratingly .net does not always show you the inner exception. Wrap your code in a try block with this catch
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); }
这篇关于ModelValidationException是未处理的用户code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!