[英]Function Returning a null Entity Error
我在這個問題上停留了幾天,感到非常沮喪,所以也許有人可以比我更好地看到它。 這是一個用C#編寫並使用實體框架的應用程序。 該代碼應該做的一些背景工作是:
該應用程序適用於石油卡車運輸行業,他們將每周/每天的產量報告並保存在數據庫中。 報告可以基於單位或井等。
無論如何,下面是我認為是問題所在的代碼。
/// <summary>
/// Returns a Production entity if one exists or null if it doesnt exist
/// </summary>
/// <returns></returns>
private Production GetProduction(DateTime dt)
{
Production existingProduction;
var qry = _db.Productions.AsNoTracking().Where(x => x.ProductionDate == dt);
if (IsUnitSelected)
existingProduction = qry.Where(x => x.UnitID == SelectedUnit.Key && x.Well == null).FirstOrDefault();
else
existingProduction = qry.Where(x => x.WellID == SelectedWell.Key && x.Unit == null).FirstOrDefault();
return existingProduction;
}
基本上,這段代碼是假設找到與選定的一周中的選定日期相對應的生產實體,然后將其返回,然后將其添加到一個名為existingProduction的Production變量中,但是如果找不到,則返回null。
下面的代碼是設置GetProduction參數時所使用的值的聲明:
var containers = _db.SourceContainers.ToList();
//Gets the currently selected Day
var view = (ProductionEntryView)this.GetView();
var date = view.SelectedWeekDay.Key;
foreach (var productionItem in Data.Productions)
{
//If Weekly Mode is on && Only validate data for the current day selected
if (!saveAll && !productionItem.Key.Equals(date))
continue;
Production existingProduction = GetProduction(productionItem.Key);
existingProduction.ProductionDate = productionItem.Key;
existingProduction.IsRunning = productionItem.Value.IsRunning.Value;
existingProduction.Remarks = productionItem.Value.Remarks;
所以畢竟,我一直得到錯誤,因為GetProduction一直返回null並將其添加到existingProduction。 因此,如果有人可以幫助我,甚至指導我找到一種更好的解決方案的方法,那也是很好的選擇。 我對Entity和C#不太熟悉,所以任何建議都很棒。 謝謝
在嘗試對existingProduction
做任何事情之前,我絕對會用null
檢查來包裝existingProduction
的用法:
Production existingProduction = GetProduction(productionItem.Key);
if (existingProduction != null)
{
existingProduction.ProductionDate = productionItem.Key;
existingProduction.IsRunning = productionItem.Value.IsRunning.Value;
existingProduction.Remarks = productionItem.Value.Remarks;
// any other code that tries to use the existingProduction variable here
}
當然,如果您認為應該獲取非null值時從GetProduction()
返回null,那就是另一個問題。 上面的代碼僅在existingProduction
結尾為null
時避免了null引用異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.