[英]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.