在Entity Framework 6中编辑对象

时间:2015-10-22 09:23:18

标签: asp.net-mvc entity-framework-6

我有一个对象Employee,其中包含很多关于Employee的信息,例如他的登录名,姓名,姓氏,电子邮件地址等。

在检索员工编辑页面上的所有信息后,我会调用以下内容来更新对象:

 public Employee Edit(Employee objEmployee) // Work on EDIT
 {
    var Original = Get(objEmployee.Login);
    _entities.Employees.Add(objEmployee);           
    _entities.SaveChanges();
    return objEmployee;
 }

一旦达到SaveChanges(),我就会得到以下信息:

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 CRAWebSiteMVC.Models.EntityEmployeeManagerRepository.Edit(Employee objEmployee) in c:\Users\kade\Source\Workspaces\InfoCubedProjects\CRA\CRAWebSiteMVC\Models\Employee\EntityEmployeeManagerRepository.cs:line 26
       at CRAWebSiteMVC.Models.EmployeeManagerService.Edit(Employee objEmployee) in c:\Users\kade\Source\Workspaces\InfoCubedProjects\CRA\CRAWebSiteMVC\Models\Employee\EmployeeManagerService.cs:line 113
  InnerException: System.Data.Entity.Core.UpdateException
       HResult=-2146233087
       Message=An error occurred while updating the entries. See the inner exception for details.
       Source=EntityFramework
       StackTrace:
            at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
            at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
            at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
            at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
            at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__d()
            at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
            at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
            at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClassb.<SaveChangesInternal>b__8()
            at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
            at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
            at System.Data.Entity.Core.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_EMPLOYEE'. Cannot insert duplicate key in object 'dbo.Employee'.
The statement has been terminated.
            Source=.Net SqlClient Data Provider
            ErrorCode=-2146232060
            Class=14
            LineNumber=1
            Number=2627
            Procedure=""
            Server=MMSDEVNEW\SQL2008
            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, SqlDataReader ds)
                 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.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
                 at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
                 at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
                 at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
                 at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
                 at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
            InnerException: 
  

违反PRIMARY KEY约束'PK_EMPLOYEE'。无法在对象'dbo.Employee'中插入重复键。

导致这种情况的原因,我该如何解决?

1 个答案:

答案 0 :(得分:0)

您需要更新实体而不是重新插入它:

public Employee Edit(Employee objEmployee) // Work on EDIT
{

    _entities.Employees.Attach(objEmployee);   
    var entity = _entities.Entry(objEmployee);  
    entry.State = EntityState.Modified;      // Mark as modified

    _entities.SaveChanges();
    return objEmployee;
}