MVC Create Controller - DbContext has been disposed

2

I'm using MVC / Entity Framework, the error that is coming up is this: The operation can not be completed because the DbContext has been available

Yes the record is created, but I get that error every time I save the record. Before, (yesterday) it did not happen to me, but today I started doing that and I have not modified anything. Any other info, let me know.

  

Project Class

public class ProjectValidation
    {
      [Remote("ValidacionExistenciaMCP", "Projects", ErrorMessage = "MCP ESTÁ EN USO. Utilizar otro.")]
    [Required(ErrorMessage = "El número MCP es Requerido.")]
    public string NumberMCP { get; set; }
    [Required(ErrorMessage = "Somthing")]
    public int EngineerID { get; set; }
            [Required(ErrorMessage = "Somthing")]
    public int SiteLocationID { get; set; }
    [Required(ErrorMessage = "Somthing.")]
    public string nameProject { get; set; }
            [Required(ErrorMessage = "Somthing")]
    public string Ptype { get; set; }
            [Required(ErrorMessage = "Somthing Somthing")]
    public int Pyear { get; set; }

    public string Plink { get; set; }

    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    [GridColumn(Format = "{0:dd/MM/yyyy}")]
    [Required(ErrorMessage = "Fecha Recibido es Requerida.")]
    public Nullable<System.DateTime> Fr { get; set; }

    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
    [Required(ErrorMessage = "Fecha Completado es Requerida.")]
    public Nullable<System.DateTime> Fc { get; set; }

    public byte[] MCPcontent { get; set; }
    public string Proj { get; set; }
    public string ContentType { get; set; }
}
  

Controller Create

public ActionResult Create()
        {
            ViewBag.EngineerID = new SelectList(db.Engineers.OrderBy(b => b.eName), "EngineerID", "eName");
            ViewBag.SiteLocationID = new SelectList(db.SiteLocations.OrderBy(b => b.nameSL), "SiteLocationID", "nameSL");
            return View();
        }


        [HttpPost, ValidateAntiForgeryToken]
       public ActionResult Create(Project mcpc, HttpPostedFileBase file, [Bind(Include = "ProjectID,NumberMCP,EngineerID,SiteLocationID,nameProject,Ptype,Pyear,Plink, Fr, Fc, MCPcontent, Proj, ContentType")] Project project)
        {
            try
            {
                if (seg.ValidaAcceso(Session["AppCode"].ToString(), Convert.ToInt16(Session["UsrRol"]), "Crear"))
                {
                    if (ModelState.IsValid && file != null && file.ContentLength > 0)
                    {
                            string ds = file.FileName.Substring(file.FileName.Length - 3);
                            string p = string.Empty;
                            p = Server.MapPath("~/UploadFiles/");
                            file.SaveAs(p + file.FileName);

                            if (file.ContentLength > 0)
                            {
                                BinaryReader br = new BinaryReader(file.InputStream);
                                byte[] buffer = br.ReadBytes(file.ContentLength);

                                using (db)
                                {

                                    mcpc.Proj = file.FileName;
                                    mcpc.ContentType = file.ContentType;
                                    mcpc.MCPcontent = buffer;
                                    db.Projects.Add(mcpc);
                                    db.SaveChanges();
                                }

                            }

                            ViewBag.EngineerID = new SelectList(db.Engineers.OrderBy(b => b.eName), "EngineerID", "eName", project.EngineerID);
                            ViewBag.SiteLocationID = new SelectList(db.SiteLocations.OrderBy(b => b.nameSL), "SiteLocationID", "nameSL", project.SiteLocationID);


                            #region logueando accion
                            Seguridad.CreateLog("Project", Seguridad.SerializeToJson(project), Seguridad.GetEventoIDByName("Crear"), project.ProjectID, Session["UsrName"].ToString(), Session["rIP"].ToString());
                            #endregion

                            return RedirectToAction("Index");
                        } 
                    else
                    {
                        TempData["Message"] = "No se elegió ningún archivo.";
                        return RedirectToAction("Create");
                    }

                             }

                 else
                    {
                        return seg.NotAccess();

                    }

            }

            catch  {

                return View("Index");

            }

            }
  

ERROR TRACE

     

The operation can not be completed because the DbContext has been   disposed.

     

Description: An unhandled exception occurred during the execution of   the current web request. Please review the stack trace for more   information about the error and where it originated in the code.

     

Exception Details: System.InvalidOperationException: The operation   can not be completed because the DbContext has been disposed.

     

Source Error:

     

An unhandled exception was generated during the execution of the   current web request. Information about the origin and location of   The exception can be identified using the exception stack trace below.

     

Stack Trace:

     

[InvalidOperationException: The operation can not be completed because   the DbContext has been disposed.]
  System.Data.Entity.Internal.LazyInternalContext.InitializeContext ()   +1067 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType (Type   entityType) +25
  System.Data.Entity.Internal.Linq.InternalSet 1.Initialize() +77
System.Data.Entity.Internal.Linq.InternalSet
1.get_InternalContext ()   +21 System.Data.Entity.Infrastructure.DbQuery 1.System.Linq.IQueryable.get_Provider() +59 System.Linq.Queryable.OrderBy(IQueryable 1 source, Expression 1 keySelector) +61
PMPDI.Controllers.ProjectsController.Create(Project mcpc, HttpPostedFileBase file, Project project) in \nttappsweb0009\PMPDI\Controllers\ProjectsController.cs:145
lambda_method(Closure , ControllerBase , Object[] ) +240
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary
2 parameters) +229
  System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod (ControllerContext   controllerContext, ActionDescriptor actionDescriptor, IDictionary 2 parameters) +35
System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +39
System.Web.Mvc.Async.WrappedAsyncResult
2.CallEndDelegate (IAsyncResult   asyncResult) +67
  System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod (IAsyncResult   asyncResult) +42
  System.Web.Mvc.Async.AsyncInvocationWithFilters.b__3d ()   +72 System.Web.Mvc.Async. < > c__DisplayClass46.b__3f ()   +385 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters (IAsyncResult   asyncResult) +69
  System.Web.Mvc.Async. < > c__DisplayClass2b.b__1c ()   +38 System.Web.Mvc.Async. < > c__DisplayClass21.b__1e (IAsyncResult   asyncResult) +185
  System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction (IAsyncResult   asyncResult) +59
  System.Web.Mvc.Controller.b__1d (IAsyncResult   asyncResult, ExecuteCoreState innerState) +29
  System.Web.Mvc.Async.WrappedAsyncVoid 1.CallEndDelegate(IAsyncResult asyncResult) +65
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +73 System.Web.Mvc.Async.WrappedAsyncVoid
1.CallEndDelegate (IAsyncResult   asyncResult) +36 System.Web.Mvc.Controller.EndExecute (IAsyncResult   asyncResult) +59
  System.Web.Mvc.MvcHandler.b__5 (IAsyncResult   asyncResult, ProcessRequestState innerState) +43
  System.Web.Mvc.Async.WrappedAsyncVoid'1.CallEndDelegate (IAsyncResult   asyncResult) +65
  System.Web.Mvc.MvcHandler.EndProcessRequest (IAsyncResult asyncResult)   +38 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute ()   +607 System.Web.HttpApplication.ExecuteStep (IExecutionStep step, Boolean & completedSynchronously) +134

    
asked by rxfeminine 23.11.2017 в 14:47
source

1 answer

1

When you receive a file, you have a condition if it true then the database context will enter a %%% block which will cause the connection to close:

if (file.ContentLength > 0)
{
    //...
    using (db)
    {
        //...
        db.SaveChanges();
    }

}

Now, the database connection is also used below and when you want to consult, and the connection will be closed.

Delete the using or declare in using at the beginning of the method so that it closes when the method finishes executing:

[HttpPost, ValidateAntiForgeryToken]
public ActionResult Create(Project mcpc, HttpPostedFileBase file, [Bind(Include = "ProjectID,NumberMCP,EngineerID,SiteLocationID,nameProject,Ptype,Pyear,Plink, Fr, Fc, MCPcontent, Proj, ContentType")] Project project)
{
    try
    {
        // lo declaramos al inicio del metodo para que se cierre cuando termine de ejecutarse el metodo y no antes
        using(db)
        {

            if (seg.ValidaAcceso(Session["AppCode"].ToString(), Convert.ToInt16(Session["UsrRol"]), "Crear"))
            {
                if (ModelState.IsValid && file != null && file.ContentLength > 0)
                {
                        string ds = file.FileName.Substring(file.FileName.Length - 3);
                        string p = string.Empty;
                        p = Server.MapPath("~/UploadFiles/");
                        file.SaveAs(p + file.FileName);

                        if (file.ContentLength > 0)
                        {
                            BinaryReader br = new BinaryReader(file.InputStream);
                            byte[] buffer = br.ReadBytes(file.ContentLength);

                            mcpc.Proj = file.FileName;
                            mcpc.ContentType = file.ContentType;
                            mcpc.MCPcontent = buffer;
                            db.Projects.Add(mcpc);
                            db.SaveChanges();
                        }

                        ViewBag.EngineerID = new SelectList(db.Engineers.OrderBy(b => b.eName).ToList(), "EngineerID", "eName", project.EngineerID);
                        ViewBag.SiteLocationID = new SelectList(db.SiteLocations.OrderBy(b => b.nameSL).ToList(), "SiteLocationID", "nameSL", project.SiteLocationID);


                        #region logueando accion
                        Seguridad.CreateLog("Project", Seguridad.SerializeToJson(project), Seguridad.GetEventoIDByName("Crear"), project.ProjectID, Session["UsrName"].ToString(), Session["rIP"].ToString());
                        #endregion

                        return RedirectToAction("Index");
                    } 
                else
                {
                    TempData["Message"] = "No se elegió ningún archivo.";
                    return RedirectToAction("Create");
                }

                         }

                else
                {
                    return seg.NotAccess();

                }
        }

    }
    catch {
        return View("Index");
    }
}
    
answered by 23.11.2017 / 14:58
source