2015-05-07 37 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

相關問題