2015-05-07 35 views
-1

突然间,我收到一个错误:未将对象引用设置为对象的实例。我正在使用实体框架6.0,一切正常,并突然一切停止代码:实体框架6.0 FirstOrDefault()对象引用未设置为对象的实例

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(); 
} 

任何人都知道什么可以改变?我见过的其他线程有管窥他们的堆栈跟踪,但我的没有它,堆栈跟踪:

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

'价格'不应该'null'。你有没有检查你是否有'db'的问题。可能是这个对象为空? –

+1

代码永远不会停止工作“突然间”。 _东西改变了,我们无法从你所展示的内容中弄清楚。去调试,请参阅[重复](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it)提示如何做到这一点。 – CodeCaster

+0

@xxMUROxx,为了更加清晰,我简化了问题,什么是中断,就像在列表中调用FirstOrDefault()函数一样简单。 – Morgs

回答

0

确定错误的推移与FirstOrDefault()行了?

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

这里,异常将如果db被抛出,或db.Prices,为空。在这里使用??运算符毫无用处,因为ToList()总是返回一个列表实例。

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

Price构造函数会抛出异常吗?

+0

为了更加清晰,我简化了这个问题,破解的过程与调用列表上的FirstOrDefault()函数一样简单。 – Morgs

+0

@Morgs可以'Price'构造函数抛出一个异常? –

+0

不,构造函数是空的... – Morgs

相关问题