Error updating Entity entries

Asked

Viewed 1,763 times

0

inserir a descrição da imagem aquiI’m trying to insert some data from some files by Entity, but it keeps giving this error:

Method:

internal void AddArquivo(Model.Arquivo arquivo)
    {
        using (var ctx = new TESTEntities())
        {
            var versao = arquivo.ArquivoVersoes[0];
            ctx.ARQUIVO.Add(new ARQUIVO()
            {
                ARQUIVO_GUID = arquivo.ARQUIVO_GUID,
                ARQUIVO_VERSAO = new ARQUIVO_VERSAO()
                {
                    ARQUIVO_GUID = arquivo.ARQUIVO_GUID,
                    ARQUIVO_VERSAO_GUID = versao.ARQUIVO_VERSAO_GUID,
                    ARQUIVO = versao.ARQUIVO,
                    DATAHORA = versao.DATAHORA,
                    TAMANHO = versao.TAMANHO,
                    USUARIO_PESSOA_GUID = versao.USUARIO_PESSOA_GUID
                },
                DIRETORIO_GUID = arquivo.DIRETORIO_GUID,
                EXTENSAO = arquivo.EXTENSAO,
                IS_STREAM = arquivo.IS_STREAM,
                TAG = arquivo.TAG,
                TIPO_DE_ARQUIVO_GUID = arquivo.TipoDeArquivo.TIPO_DE_ARQUIVO_GUID,
                ULT_ARQUIVO_VERSAO_GUID = arquivo.ULT_ARQUIVO_VERSAO_GUID,
                URL = arquivo.URL,
                XARQUIVO = arquivo.XARQUIVO
            });
            ctx.SaveChanges();
        }
    }
}


ERRO: "Erro ao atualizar as entradas. Consulte a exceção interna para obter detalhes."

remembering that my primary keys are like varchar, and are not Identity

System.Data.Entity.Infrastructure.DbUpdateException was caught HResult=-2146233087 Message=Erro ao atualizar as entradas. Consulte a exceção interna para obter detalhes. Source=EntityFramework StackTrace: em     
System.Data.Entity.Internal.InternalContext.SaveChanges() em InnerException: 
System.Data.UpdateException HResult=-2146233087 Message=Erro ao atualizar as entradas. Consulte a exceção interna para obter detalhes. Source=System.Data.Entity StackTrace: em 
System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) em 
System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options) em 
System.Data.Entity.Internal.InternalContext.SaveChanges() InnerException: 
System.Data.SqlClient.SqlException HResult=-2146232060 Message=Violation of PRIMARY KEY constraint 'ARQUIVO_VERSAO_PK'. Cannot insert duplicate key in object TEST.ARQUIVO_VERSAO'. The statement has been terminated. Source=.Net SqlClient Data Provider ErrorCode=-2146232060 Class=14 LineNumber=1 Number=2627 Procedure="" Server=192.168.10.59 State=1 StackTrace: em 
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) em 
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) em 
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) em 
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) em 
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite) em System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) em 
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) em 
System.Data.SqlClient.SqlCommand.ExecuteNonQuery() em 
System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues) em 
System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter) InnerException:
  • You over-wrote the OnModelCreating of GEDEntities? It may be a validation error. Otherwise, you need to go to us InnerException to see what happened, if it is not detailed enough, try this to show in depth the errors that occurred: http://blogs.infosupport.com/improving-dbentityvalidationexception/

  • What’s the mistake? Can you please put it in your question?

  • I didn’t overwrite Onmodelcreating that would be what?

  • @Warlock, in this case it is important put to Innerexception, ie the one that actually contains useful information about the error. However when it comes to Entity Framework, I will ask you to make a Try with 2 catch, one for Dbentityvalidationexception and one for Exception.

  • As I see this innerexception?

  • I put a catch for Dbentityvalidationexception, but in debug it already goes to Exception

  • Put a breakpoint in the Exception, and expand it until you get the innermost exception.

  • I will post the complete error

  • an example of how to take an Innerexception: https://dotnetfiddle.net/9CMNuR

  • posted the error...

  • 1

    Cannot Insert Duplicate key in Object TEST.ARQUIVO_VERSAO'. The statement has been terminated. You are trying to insert a duplicate Key into the Bank.

  • 1
  • that error is in the method I posted?

  • @Warlock What is the primary key of ArquivoVersao?

  • @Warlock, could you reset the entity diagram?

  • ARQUIVO_VERSAO_GUID is the PK, posted the diagram

  • posting a response.

Show 12 more comments

2 answers

0


The error is quite clear:

System.Data.SqlClient.SqlException HResult=-2146232060 Message=Violation of PRIMARY KEY constraint 'ARQUIVO_VERSAO_PK'. Cannot insert duplicate key in object TEST.ARQUIVO_VERSAO'. The statement has been terminated. 

It means that here:

            ARQUIVO_VERSAO = new ARQUIVO_VERSAO()
            {
                ARQUIVO_GUID = arquivo.ARQUIVO_GUID,
                ARQUIVO_VERSAO_GUID = versao.ARQUIVO_VERSAO_GUID, // Isto já existe no banco
                ARQUIVO = versao.ARQUIVO,
                DATAHORA = versao.DATAHORA,
                TAMANHO = versao.TAMANHO,
                USUARIO_PESSOA_GUID = versao.USUARIO_PESSOA_GUID
            },

The right thing would be for you to generate one Guid new for each new inserted version. As the column is String, still needs one more conversion:

            ARQUIVO_VERSAO = new ARQUIVO_VERSAO()
            {
                ARQUIVO_GUID = arquivo.ARQUIVO_GUID,
                ARQUIVO_VERSAO_GUID = Guid.NewGuid().ToString(),
                ARQUIVO = versao.ARQUIVO,
                DATAHORA = versao.DATAHORA,
                TAMANHO = versao.TAMANHO,
                USUARIO_PESSOA_GUID = versao.USUARIO_PESSOA_GUID
            },
  • ops, from conversion error to string

  • converted, I’ll test it

  • 1

    @Ciganomorrisonmendez, for some reason he saves and manipulates Guids as text, just don’t ask me why.

  • worked well worth ...

  • Giving another Entity Exception, I must create another theme?

  • @Ciganomorrisonmendez, the only problem I see in this answer, is that you are discarding the PK that is in the Archive. If this is an integration or conciliation program, this can cause many problems.

  • @Warlock should. It’s another problem now.

  • I figured that out Toby, but at the time it solved, and I don’t think I’m gonna have a problem with that.

  • @Tobymosque I do not know what makes his logic. To answer this does not seem to be important.

  • 1

    @Warlock, this "I think" gave me an impression that it lacks an understanding of the project as a whole, in its place would look for the architect of this system.

Show 5 more comments

0

You are trying to insert an ARQUIVO_VERSAO object that already exists, in this case you need to check if it already exists in the Database. You can do it as follows:

using (var ctx = new TESTEntities())
{
    var versaoAux = arquivo.ArquivoVersoes[0];
    var versao = ctx.ARQUIVO_VERSAO.Find(versaoAux.ARQUIVO_VERSAO_GUID);
    if (versao == default(ARQUIVO_VERSAO)) 
    {       
        versao = new ARQUIVO_VERSAO()
        {
            ARQUIVO_GUID = arquivo.ARQUIVO_GUID,
            ARQUIVO_VERSAO_GUID = versaoAux.ARQUIVO_VERSAO_GUID,
            ARQUIVO = versaoAux.ARQUIVO,
            DATAHORA = versaoAux.DATAHORA,
            TAMANHO = versaoAux.TAMANHO,
            USUARIO_PESSOA_GUID = versaoAux.USUARIO_PESSOA_GUID
        };
    }

    ctx.ARQUIVO.Add(new ARQUIVO()
    {
        ARQUIVO_GUID = arquivo.ARQUIVO_GUID,
        ARQUIVO_VERSAO = versao,
        DIRETORIO_GUID = arquivo.DIRETORIO_GUID,
        EXTENSAO = arquivo.EXTENSAO,
        IS_STREAM = arquivo.IS_STREAM,
        TAG = arquivo.TAG,
        TIPO_DE_ARQUIVO_GUID = arquivo.TipoDeArquivo.TIPO_DE_ARQUIVO_GUID,
        ULT_ARQUIVO_VERSAO_GUID = arquivo.ULT_ARQUIVO_VERSAO_GUID,
        URL = arquivo.URL,
        XARQUIVO = arquivo.XARQUIVO
    });
    ctx.SaveChanges();
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.