Entity Framework 6.0 FirstOrDefault()对象引用未设置为对象的实例[duplicate]

时间:2021-10-13 16:53:58

This question already has an answer here:

这个问题在这里已有答案:

All of a sudden I'm getting an error: Object reference not set to an instance of an object. I'm using Entity Framework 6.0 and everything was working and all of a sudden everything stopped code:

突然间我收到一个错误:对象引用未设置为对象的实例。我正在使用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();
}

Anyone knows what could've changed? I've seen other threads have Glimpse in their stack trace but mine doesn't have it, Stack Trace:

谁知道什么可以改变?我已经看到其他线程在他们的堆栈跟踪中有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)

1 个解决方案

#1


Are you sure the error goes on the line with FirstOrDefault()?

你确定错误与FirstOrDefault()一致吗?

List<Price> prices = db.Prices.ToList() ?? new List<Price>();

Here, an exception will be thrown if db, or db.Prices, is null. Using a ?? operator is useless here, because ToList() always returns a list instance.

这里,如果db或db.Prices为null,则抛出异常。用一个 ??运算符在这里没用,因为ToList()总是返回一个列表实例。

Price price = prices.FirstOrDefault() ?? new Price() { Amount = 0 };

Could Price constructor be throwing an exception?

Price构造函数可以抛出异常吗?

#1


Are you sure the error goes on the line with FirstOrDefault()?

你确定错误与FirstOrDefault()一致吗?

List<Price> prices = db.Prices.ToList() ?? new List<Price>();

Here, an exception will be thrown if db, or db.Prices, is null. Using a ?? operator is useless here, because ToList() always returns a list instance.

这里,如果db或db.Prices为null,则抛出异常。用一个 ??运算符在这里没用,因为ToList()总是返回一个列表实例。

Price price = prices.FirstOrDefault() ?? new Price() { Amount = 0 };

Could Price constructor be throwing an exception?

Price构造函数可以抛出异常吗?