我突然收到错误:对象引用未设置为对象的实例。我正在使用Entity Framework 6.0,一切正常,一切都停止了代码:
List<Price> prices = db.Prices.ToList() ?? new List<Price>();
if ( prices != null && prices.Any() )
{
// Price is a data model generated by edmx
Price price = prices.FirstOrDefault();
}
任何人都知道可以改变什么?我已经看到其他线程在他们的堆栈跟踪中有Glimpse,但我的没有它,Stack Trace:
at ASP._Page_Views_FAStock__VehiclePrices_cshtml.Execute() in c:\wamp\www\netauto.co.za\apcloud.co.za\ApCloud\ApCloud.SM.UI\Views\FAStock\_VehiclePrices.cshtml:line 96
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
答案 0 :(得分:0)
您确定错误与FirstOrDefault()
一致吗?
List<Price> prices = db.Prices.ToList() ?? new List<Price>();
此处,如果db
或db.Prices
为空,则会抛出异常。在这里使用??
运算符是没用的,因为ToList()
总是返回一个列表实例。
Price price = prices.FirstOrDefault() ?? new Price() { Amount = 0 };
Price
构造函数可以抛出异常吗?