问题描述
添加新记录时收到以下错误
I received the following error while adding new record
System.Data.Entity.Infrastructure.DbUpdateException was caught
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at Navigation.RepositoryBase`2.Add(T entity) in c:\Users\afahmy\Documents\Visual Studio 2012\Projects\Navigation\REpositoryBase.cs:line 174
InnerException: System.Data.UpdateException
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=System.Data.Entity
StackTrace:
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
Message=Violation of PRIMARY KEY constraint 'PK_dbo.Priorities'. Cannot insert duplicate key in object 'dbo.Priorities'. The duplicate key value is (55c9b08f-1133-4246-9d0b-4f3e5192ffa5).
The statement has been terminated.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=14
LineNumber=1
Number=2627
Procedure=""
Server=dbsrv
State=1
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
InnerException:
代码如下
public virtual OperationResult Add(T entity)
{
OperationResult opStatus = new OperationResult { Result = QueryResult.Succeeded };
try
{
DataContext.Set<T>().Add(entity);
opStatus.Result = (DataContext.SaveChanges() > 0) ? QueryResult.Succeeded : QueryResult.Failed;
}
catch (Exception exp)
{
opStatus.ExceptionMessage = string.Format(" Error Adding {0}", exp.Message);
opStatus.Result = QueryResult.Failed;
}
return opStatus;
}
推荐答案
显然, entity
对象已经从数据库中获取。如果将它添加到上下文中,它将获得 EntityState.Added
,这意味着EF将尝试插入它。显然,您生成主键值客户端(即不在数据库中),因此EF尝试使用现有的PK值插入。
Apparently, the entity
object has been fetched from the database before. If you add it to the context it will get EntityState.Added
, which means that EF will try to insert it. And apparently you generate a primary key value client-side (i.e. not in the database), so EF tries to insert it with an existing PK value.
由于这是 DbContext
API(从Set方法显而易见,但总是有助于显式标记),您可以使用方法让EF知道是否对象需要插入或更新。
Since this is the DbContext
API (apparent from the Set method, but always helpful to tag explicitly) you can use the IDbSetExtensions.AddOrUpdate
method to let EF figure out whether the object needs to be inserted or updated.
这篇关于调用saveChanges时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!