本文介绍了用相同的密钥对象已存在于objectstatemanager。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收到以下错误而使用实体框架更新两个表 -
My code
public void UpdatePaymentTransaction(PaymentTransaction paymentTransaction)
{
using (var context = DataObjectFactory.CreateContext())
{
var entity = context.PaymentTransactionEntities.Where(c => c.Id == paymentTransaction.Id).SingleOrDefault();
entity.PartyId = paymentTransaction.PartyId;
entity.TotalAmount = paymentTransaction.TotalAmount;
entity.RequestDate = paymentTransaction.RequestDate;
entity.ResponseDate = paymentTransaction.ResponseDate;
context.PaymentTransactionEntities.ApplyCurrentValues(entity);
context.SaveChanges();
if (paymentTransaction.PaymentGatewayOrderId != null)
{
PaymentTransactionContractEntity paymentTransactionContractEntity = new PaymentTransactionContractEntity();
string[] contractIds = paymentTransaction.PaymentGatewayOrderId.Split('-');
foreach (var contractId in contractIds)
{
paymentTransactionContractEntity.PaymentTransactionId = entity.Id;
paymentTransactionContractEntity.ContractId = Convert.ToInt32(contractId);
context.PaymentTransactionContractEntities.AddObject(paymentTransactionContractEntity);
context.SaveChanges();
}
}
}
}
解决方案
Try this instead:
public void UpdatePaymentTransaction(PaymentTransaction paymentTransaction)
{
using (var context = DataObjectFactory.CreateContext())
{
var entity = context.PaymentTransactionEntities.Where(c => c.Id == paymentTransaction.Id).SingleOrDefault();
entity.PartyId = paymentTransaction.PartyId;
entity.TotalAmount = paymentTransaction.TotalAmount;
entity.RequestDate = paymentTransaction.RequestDate;
entity.ResponseDate = paymentTransaction.ResponseDate;
// Either use previous for rows or following row. Both are not needed
//context.PaymentTransactionEntities.ApplyCurrentValues(entity);
context.SaveChanges();
if (paymentTransaction.PaymentGatewayOrderId != null)
{
string[] contractIds = paymentTransaction.PaymentGatewayOrderId.Split('-');
foreach (var contractId in contractIds)
{
// Create new instance for each loop otherwise only first contract
// is considered as insert and all following contracts only modifies
// the first one = reason for your exception
PaymentTransactionContractEntity paymentTransactionContractEntity = new PaymentTransactionContractEntity();
paymentTransactionContractEntity.PaymentTransactionId = entity.Id;
paymentTransactionContractEntity.ContractId = Convert.ToInt32(contractId);
context.PaymentTransactionContractEntities.AddObject(paymentTransactionContractEntity);
context.SaveChanges();
}
}
}
}
这篇关于用相同的密钥对象已存在于objectstatemanager。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!