var existingRecord = await this.GetGoodsDelivery(goodsDelivery.Id);
var detailIdsInNewRecord = new HashSet<int>(goodsDelivery.GoodsDeliveryDetail.Select(d => d.Id));
foreach(var record in existingRecord.GoodsDeliveryDetail.ToList())
{
if(!detailIdsInNewRecord.Contains(record.Id))
{
inventoryContext.GoodsDeliveryDetail.Remove(record);
}
}
foreach(var newrecord in goodsDelivery.GoodsDeliveryDetail.ToList())
{
if(newrecord.Id == 0)
{
var newDetailRow = new GoodsDeliveryDetail();
var newrecordType = newrecord.GetType();
var properties = newrecordType.GetProperties();
foreach (var property in properties)
{
var value = property.GetValue(newrecord);
property.SetValue(newDetailRow, value);
}
goodsDelivery.GoodsDeliveryDetail.Add(newDetailRow);
}
}
inventoryContext.GoodsDelivery.Update(goodsDelivery);
await inventoryContext.SaveChangesAsync();
error occurs
System.InvalidOperationException: ‘The instance of entity type ‘GoodsDelivery’ cannot be tracked because another instance with the same key value for {‘Id’} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using ‘DbContextOptionsBuilder.EnableSensitiveDataLogging’ to see the conflicting key values.’
var existingRecord = await this.GetGoodsDelivery(goodsDelivery.Id);
var detailIdsInNewRecord = new HashSet<int>(goodsDelivery.GoodsDeliveryDetail.Select(d => d.Id));
foreach(var record in existingRecord.GoodsDeliveryDetail.ToList())
{
if(!detailIdsInNewRecord.Contains(record.Id))
{
inventoryContext.GoodsDeliveryDetail.Remove(record);
}
}
foreach(var newrecord in goodsDelivery.GoodsDeliveryDetail.ToList())
{
if(newrecord.Id == 0)
{
var newDetailRow = new GoodsDeliveryDetail();
var newrecordType = newrecord.GetType();
var properties = newrecordType.GetProperties();
foreach (var property in properties)
{
var value = property.GetValue(newrecord);
property.SetValue(newDetailRow, value);
}
goodsDelivery.GoodsDeliveryDetail.Add(newDetailRow);
}
}
inventoryContext.GoodsDelivery.Update(goodsDelivery);
await inventoryContext.SaveChangesAsync();
Zahid Ahmed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.