我正在尝试为以下代码创建一个通用方法:
foreach (var glitter in glitterpurchase.GlitterPurchaseDetails)
{
var glitterInventory = _db.GlitterInventoriesRepository.GetAll(m => m.GlitterId == glitter.GlitterId);
if (!glitterInventory.Any())
{
var newInventory = new GlitterInventory
{
GlitterId = glitter.GlitterId,
Quantity = glitter.Quantity,
TotalAmount = (decimal)glitter.Quantity * glitter.UnitPrice,
UnitPrice = glitter.UnitPrice,
CreatedBy = User.Identity.Name,
CreatedDate = DateTime.Now,
};
_db.GlitterInventoriesRepository.Insert(newInventory);
}
else
{
var updateInventory = glitterInventory.First();
updateInventory.Quantity += glitter.Quantity;
updateInventory.TotalAmount += (decimal)glitter.Quantity * glitter.UnitPrice;
updateInventory.UnitPrice = (decimal)updateInventory.Quantity / updateInventory.TotalAmount;
updateInventory.UpdatedBy = User.Identity.Name;
updateInventory.UpdatedDate = DateTime.Now;
_db.GlitterInventoriesRepository.Update(updateInventory);
}
}
上面的代码只是简单地更新了库存。我想制作一个通用方法,以便我可以调用该方法并更新不同项(类)的库存。我不熟悉泛型,经过研究,我写了下面的代码:
public virtual void UpdateInventory<PurchasedEntity, Inventory>(IEnumerable<PurchasedEntity> purchaseDetails, GenericRepository<Inventory> inventory, Expression<Func<Inventory, bool>> filterForInventory)
where PurchasedEntity : class
where Inventory : class
{
foreach (var item in purchaseDetails)
{
var glitterInventory = inventory.GetAll(filterForInventory);
if (!glitterInventory.Any())
{
var newInventory = (Inventory)Activator.CreateInstance(typeof(Inventory), new object[]
{
GlitterId = item.GlitterId,
Quantity = item.Quantity,
TotalPrice = (decimal)item.Quantity * item.UnitPrice,
UnitPrice = item.UnitPrice,
CreatedBy = User.Identity.Name,
CreatedDate = DateTime.Now,
});
inventory.Insert(newInventory);
}
else
{
var updateInventory = glitterInventory.First();
updateInventory.Quantity += item.Quantity;
updateInventory.TotalAmount += (decimal)item.Quantity * item.UnitPrice;
updateInventory.UnitPrice = (decimal)updateInventory.Quantity / updateInventory.TotalAmount;
updateInventory.UpdatedBy = User.Identity.Name;
updateInventory.UpdatedDate = DateTime.Now;
inventory.Update(updateInventory);
}
}
}
问题是我收到以下错误:
'PurchasedEntity' does not contain a definition for 'GlitterId' and no extension method 'GlitterId' accepting a first argument of type 'PurchasedEntity' could be found (are you missing a using directive or an assembly reference?)
如何删除此错误并获取该类的属性?
我甚至不知道我写的代码是否有用,如果你能改进它,那就太好了,那就太好了。感谢。