Problems when adding a new record

0

Hello again community,

I am learning entity framework and I do an exercise where I keep a file with x documents and that document has x images.

When wanting to insert new documents to an existing file, I have the following error:

  

An unhandled exception of type 'System.ObjectDisposedException' occurred in EntityFramework.dll

     

Additional information: The ObjectContext instance has been available and can not be used for operations that require a connection.

I have a form where the files are ready, then by selecting one and clicking on edit, I pass the selected file to a new detail window, like this:

Detalles exp = new Detalles(bExpedientes[index]);

bFiles is a binding list that contains all the existing files, it is filled in like this:

 public static List<Expediente> GetExpedientes()
    {
        Entities context = new Entities();
        List<Expediente> exp = new List<Expediente>();
        using (context)
        {
            try
            {
                exp = context.Expediente.ToList();
            }
            catch (Exception)
            {
                return null;
            }
            return exp;
       }
    }

Then, in details, I have a button to add new documents like this:

expediente.Documentos.Add(new Documento { NombreDocumento = txtNomDoc.Text, FechaCreacion = DateTime.Now, idExpediente = idExpediente })

where file, is an instance of the file class generated by EF. that's where the problem comes in, when executing that line, pull the exception mentioned above. I understand that it may be because of the use I make when extracting the files. But some idea of how to solve it?

Then I save all those new documents in a binding list called bDocuments, like this:

Doc = expediente.Documentos.ToList();
            dgvDocumentos.AutoGenerateColumns = false;
            bDocumentos = new BindingList<Documento>(Doc);
            dgvDocumentos.DataSource = bDocumentos;

and then clicking on a save button, pass the lists to a function that will do the saving. When I insert new files with new documents and new images I have no problems. But when adding new documents to an existing file if!

What the save button does is the following:

General.GuardarDatos(bDocumentos, bArchivo);

Here, I pass the lists. The archive is not relevant at the moment. The SaveData method does the following:

public static void GuardarDatos(Expediente expediente,BindingList<Documento> documentos, BindingList<Archivo> archivos)
    {
        Entities context = new Entities();
        using (context)
        {
            foreach(var documento in documentos)
            {
                if(documento.idDocumento == 0)
                {
                    context.Documento.Add(documento);
                }
                else
                {
                    DocumentoNG.actualizarDocumento(documento);
                }
                foreach(var archivo in archivos)
                {
                    if (documento.idDocumento == 0)
                    {
                        context.Archivo.Add(archivo);
                    }
                    else
                    {
                        ArchivoNG.actualizarArchivo(archivo);
                    }
                }
            }
            context.SaveChanges();
        }
    }

If I remove the using, the error is thrown when executing the updateDocument line, however, it is another that is:

An unhandled exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll

Additional information: An entity object can not be referenced by multiple instances of IEntityChangeTracker.

and that method does the following:

 public static void actualizarDocumento(Documento documento)
    {
        Entities context = new Entities();
        using (context)
        {
            context.Documento.Attach(documento);
            var registro = context.Entry(documento);
            registro.Property(t => t.NombreDocumento).IsModified = true;
            context.SaveChanges();
        }
    }

The entity file is like this:

 public partial class Expediente
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Expediente()
    {
        this.Documentos = new HashSet<Documento>();
    }

    public int idExpediente { get; set; }
    public string NombreExpediente { get; set; }
    public System.DateTime FechaCreacion { get; set; }
    public string DuenioExpediente { get; set; }
    public int CantidadDocumento { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Documento> Documentos { get; set; }
}

The document is like this:

public partial class Documento
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Documento()
    {
        this.Archivo = new HashSet<Archivo>();
    }

    public int idDocumento { get; set; }
    public int idExpediente { get; set; }
    public string NombreDocumento { get; set; }
    public System.DateTime FechaCreacion { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Archivo> Archivo { get; set; }
    public virtual Expediente Expediente { get; set; }
}

Thanks in advance.

    
asked by Alex Varela 07.12.2017 в 18:54
source

1 answer

0

Try it like this

public static void GuardarDatos(Expediente expediente,BindingList<Documento> documentos, BindingList<Archivo> archivos)
    {
        Entities context = new Entities();
        using (context)
        {
            foreach(var documento in documentos)
            {
                if(documento.idDocumento == 0)
                {
                    context.Documento.Add(documento);
                    context.SaveChanges();
                }
                else
                {
                    DocumentoNG.actualizarDocumento(documento);
                    context.SaveChanges();
                }
                foreach(var archivo in archivos)
                {
                    if (documento.idDocumento == 0)
                    {
                        context.Archivo.Add(archivo);
                        context.SaveChanges();
                    }
                    else
                    {
                        ArchivoNG.actualizarArchivo(archivo);
                        context.SaveChanges();
                    }
                }
            }
   }
}
    
answered by 07.12.2017 в 19:04