0
我只想問一下這種錯誤。EntityFramework錯誤
對數據庫的更改已成功提交,但更新對象上下文時發生錯誤。 ObjectContext可能處於不一致的狀態。內部異常消息:由於對象的鍵值與ObjectStateManager中的另一個對象衝突,因此AcceptChanges無法繼續。在調用AcceptChanges之前確保鍵值是唯一的。
在將記錄插入用戶界面後,手動刪除到後端(SQL)時發生錯誤。下面你會找到代碼。
public async Task<ActionResult> AddCustomer([DynamicJson] dynamic data)
{
var returnJson = new ReturnJsonModel { status = "ok" };
dynamic ent = data.ent;
var customerId = string.Empty;
using (var dbContextTransaction = db.Database.BeginTransaction())
{
try
{
var customerEo = new ARCustomer();
foreach (var field in ent)
{
if (Enumerable.Contains(_signatoryKey, field.Key))
UploadSignatoryImage(field.Key, field.Value);
if (!Enumerable.Contains(_excludedKey, field.Key))
GenericExtensions.SetValue(customerEo, field.Key, field.Value);
}
//customerId = customerEo.CustomerID;
customerEo.SetCreatedStamp();
db.ARCustomers.Add(customerEo);
await db.SaveChangesAsync();
returnJson.request = new { customerEo.SeqID };
}
catch (DbEntityValidationException ex)
{
foreach (var eve in ex.EntityValidationErrors)
{
returnJson.message = string.Format("Entity of type {0} in state {1} has the following validation errors: ",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
returnJson.message = string.Format("Property {0}, Error: {1}", ve.PropertyName, ve.ErrorMessage);
}
throw;
}
catch (DbUpdateException ex)
{
returnJson.status = "error";
returnJson.message = ex.InnerErrorMessage();
}
catch (SqlException ex)
{
returnJson.status = "error";
returnJson.message = string.Format("{0} The sql errors are: {1}", ex.Message, ex.FullErrorMessage());
}
catch (Exception ex)
{
returnJson.status = "error";
returnJson.message = ex.InnerErrorMessage();
}
if (!returnJson.status.Equals("error"))
{
SaveSignatories(customerId);
if (!returnJson.status.Equals("error"))
dbContextTransaction.Commit();
}
}
return Json(returnJson);
}
嗨Ajay,但在我的數據庫表中,我有一個主鍵,身份已被設置爲是。任何其他想法如何解決這個問題? –
bs.SuspendBinding(); Data.SaveChanges(); bs.ResumeBinding(); //試試這個代碼。 –
謝謝你,但我已經解決了這個問題 –