我试图创建程序时,数据已经存在,它会更新数据,如果没有,那么它会添加数据,下面是我的代码。更新工作,但添加不工作。如果我删除更新代码,那么添加将工作
var itemLocQuantity = objERPMicroDbEntities.ItemLocationDatas.FirstOrDefault(items => items.ItemId == item.ItemId && items.LocationId == item.LocationId);
if (itemLocQuantity.ItemId == item.ItemId && itemLocQuantity.LocationId == item.LocationId) {
itemLocQuantity.Quantity += item.QuantityReceive;
}
以上是更新
if (itemLocQuantity == null)
{
itemLocQuantity = new ItemLocationData();
// create new in db
itemLocQuantity.ItemId = item.ItemId;
itemLocQuantity.Quantity = item.QuantityReceive;
itemLocQuantity.LocationId = item.LocationId;
objERPMicroDbEntities.ItemLocationDatas.Add(itemLocQuantity);
}
上面是试图添加的代码,但我的程序在尝试添加新数据时返回错误
如果整个函数是这样的:
var itemLocQuantity = objERPMicroDbEntities.ItemLocationDatas.FirstOrDefault(items => items.ItemId == item.ItemId && items.LocationId == item.LocationId);
if (itemLocQuantity.ItemId == item.ItemId && itemLocQuantity.LocationId == item.LocationId)
{
itemLocQuantity.Quantity += item.QuantityReceive;
}
if (itemLocQuantity == null)
{
itemLocQuantity = new ItemLocationData();
// create new in db
itemLocQuantity.ItemId = item.ItemId;
itemLocQuantity.Quantity = item.QuantityReceive;
itemLocQuantity.LocationId = item.LocationId;
objERPMicroDbEntities.ItemLocationDatas.Add(itemLocQuantity);
}
那么当你去插入的问题将是你的更新代码期望返回一个对象,这将失败,因为它发生在Null检查之前。您可以反转条件并使用else
条件进行更新:
var itemLocQuantity = objERPMicroDbEntities.ItemLocationDatas.SingleOrDefault(items => items.ItemId == item.ItemId && items.LocationId == item.LocationId);
if (itemLocQuantity == null) // insert.
{
itemLocQuantity = new ItemLocationData();
// create new in db
itemLocQuantity.ItemId = item.ItemId;
itemLocQuantity.Quantity = item.QuantityReceive;
itemLocQuantity.LocationId = item.LocationId;
objERPMicroDbEntities.ItemLocationDatas.Add(itemLocQuantity);
}
else // update.
{
itemLocQuantity.Quantity += item.QuantityReceive;
}
这甚至可以浓缩为:
var itemLocQuantity = objERPMicroDbEntities.ItemLocationDatas.SingleOrDefault(items => items.ItemId == item.ItemId && items.LocationId == item.LocationId);
if (itemLocQuantity == null) // insert.
{
itemLocQuantity = new ItemLocationData();
// create new in db
itemLocQuantity.ItemId = item.ItemId;
itemLocQuantity.LocationId = item.LocationId;
objERPMicroDbEntities.ItemLocationDatas.Add(itemLocQuantity);
}
itemLocQuantity.Quantity += item.QuantityReceive;
如果没有找到项,则插入它,然后在添加后,或者如果它已经存在,则更新if
之外的可更新字段。
同样,如果您正在查询并期望一个或零项,请使用SingleOrDefault
而不是FirstOrDefault
。First*
方法意味着我期望零或多个,并且我只关心第一个匹配。他们应该总是使用OrderBy*
子句来确保结果是可重复的。