Editing an object in Entity Framework 6

asp.net-mvc entity-framework-6

Question

I have an object Employee containing lots of information on an Employee, such as his Login, Name, LastName, e-mail address etc.

After retrieving all the information imputed on the edit page of an employee, I then call the following to update the object :

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

Once it reaches SaveChanges() I get the following :

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: 

Violation of PRIMARY KEY constraint 'PK_EMPLOYEE'. Cannot insert duplicate key in object 'dbo.Employee'.

What could be causing that, and how may I solve it?

1
0
10/22/2015 9:23:18 AM

Accepted Answer

You need to update the entity and not to re-insert it:

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;
}
0
10/22/2015 9:44:31 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow