logo
down
shadow

Dbcontext has been disposed when using "using Statement"


Dbcontext has been disposed when using "using Statement"

By : user2954359
Date : November 22 2020, 01:01 AM
should help you out It is disposed by the second time you call a method on a repository. A timeline is like that:
GetUserByEmailId is called, _instance is null, so it is initialized GetUserByEmailId is completed, and context is disposed. But the object still exists in _instance field UpdateUser is called, _instance is not null, so the old context is returned in using context.SaveChanges is called, but since this object of context is already disposed, the exception is thrown
code :


Share : facebook icon twitter icon
What is causing this error "The operation cannot be completed because the DbContext has been disposed"

What is causing this error "The operation cannot be completed because the DbContext has been disposed"


By : Jay Kothari
Date : March 29 2020, 07:55 AM
To fix this issue Ok, solved this issue by using raw ado.net code, so i just changed the find method from entity framework linq code to raw ado.net data access code. The error didn't occur any more, if anyone has a better solution using entity framework, please share. The find method rewritten, code below:
code :
public Variables Find(string name)
        {
            var objVariable = new Variables();

            using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringValue"].ToString()))
            {
                conn.Open();

                var sql = @" select top 1 * 
                            from SomeTable 
                            where Column1 = @Name";

                try
                {
                    var cmd = new SqlCommand(sql, conn);
                    cmd.CommandType = CommandType.Text;

                    cmd.Parameters.Add("@Name", SqlDbType.NVarChar).Value = name;

                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.HasRows)
                    {
                        if (dr.Read())
                        {
                            objVariable.Column1 = dr["Column1"].ToString();
                            objVariable.Column2 = dr["Column2"].ToString();
                        }
                    }

                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }

            return objVariable;

        }
"The operation cannot be completed because the DbContext has been disposed" exception with lazy load disabled

"The operation cannot be completed because the DbContext has been disposed" exception with lazy load disabled


By : Nathan Mcnally
Date : March 29 2020, 07:55 AM
Hope that helps Lazy and eager loading have to do with when entities related to your query (e.g. navigation properties and collections) are loaded, not when the contents of the query itself are loaded.
The IQuerable returned from your repository—whether or not you have lazy loading enabled—will not run the query on the server until it's enumerated (whether that's by getting an enumerator in a foreach loop, calling Enumerable.ToList on it, or passing it into a call to Controller.View for downstream rendering).
ToListAsync() in a DbContext using statement : "The ObjectContext disposed", How to deal?

ToListAsync() in a DbContext using statement : "The ObjectContext disposed", How to deal?


By : Ketan
Date : March 29 2020, 07:55 AM
Hope this helps You're leaving the using scope before the ToListAsync operation completes because you're not awaiting the asynchronous task, which means entities is disposed too soon (hence the object disposed exception).
You should just return the result while inside the scope and the async-await mechanism will make sure Dispose is called after the operation completes asynchronously:
code :
private async Task<List<String>> GetEntiteesAsync()
{
     using (var entities = new REPORTEntities())
     {
          return await (from user in entities.USERs
                         group user by user.entite into g
                               select g.Key).ToListAsync();
     }
}
"The operation cannot be completed because the DbContext has been disposed" #2

"The operation cannot be completed because the DbContext has been disposed" #2


By : user3707454
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You are returning an IQueryable object. Once you return, you exit your Using statement, which closes your Context. You need to enumerate using .ToList() before you exit your using statement. This will execute the query while the context is still open.
Change it to this:
code :
public List<Prueba> GetAllPruebas()
{
   using (var ctx = new OracleDbContext())
    {
        return ctx.Pruebas.ToList();
    }
}
public class OracleDbContext : DbContext
{
    public OracleDbContext()
    {
        Database.SetInitializer<OracleDbContext>(new DropCreateDatabaseAlways<OracleDbContext>());
    }

    public DbSet<Prueba> Pruebas { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("DATA");
    }
}
Autofac - Retrieving new instance of UnitOfWork - "DBcontext has been disposed error"

Autofac - Retrieving new instance of UnitOfWork - "DBcontext has been disposed error"


By : user2199381
Date : March 29 2020, 07:55 AM
wish help you to fix your issue To ensure I get a fresh instance of my UnitOfWork after each batch of operations, I retrieve a reference to my current Autofac lifetime scope and ask Autofac to give me a new lifetime scope inside a using statement, then I use Autofac to register and resolve those dependencies. Some of my services also depend on the UnitOfWork so it was important that I get fresh instances of those dependencies too.
Here's a cut-down snippet:
code :
foreach (var batch in data.Split(10))
{
    using (var scope = LifetimeScope.BeginLifetimeScope("UnitOfWork", b =>
    {
        b.RegisterType<UnitOfWork>().AsImplementedInterfaces().InstancePerLifetimeScope();
        b.RegisterType<MyService>().AsImplementedInterfaces().PropertiesAutowired().InstancePerLifetimeScope();
        b.RegisterGeneric(typeof(EntityBaseRepository<>)).As(typeof(IEntityBaseRepository<>)).InstancePerLifetimeScope();
    }))
    {
        UnitOfWork = scope.Resolve<IUnitOfWork>();
        MyService = scope.Resolve<IMyService>();

        foreach (var row in batch)
        {
            try
            {
                ParseRow(row);
            }
            catch (Exception e)
            {
                JobLogger.Error(e, "Failed to parse row. Exception: " + e.Message);
                throw;
            }

        }
    }
}
Related Posts Related Posts :
  • C# correct exception handling
  • "Could not open macro storage" when accessing using file on another machine
  • How to access other directories of hosted server
  • C# Jagged Array check if value exists/true
  • Why can't I type Clone() properly?
  • exception on accessing dictionary from list
  • Getting the immediate response from server without waiting to 200 message
  • Why am I getting exception Directory Is Not empty?
  • Could not load file or assembly 'CefSharp.dll' or one of its dependencies
  • Sending Email By Using C# in unity3D?
  • Correct usage of await async in webapi
  • Program update code issue
  • Marshal.Copy attempted to read or write protected memory At Random Times
  • Restrict Type variable to specific class or subclass
  • Horizontal text alignment in a PdfPCell
  • C# crashing with Form.show() command, ObjectDisposedException - Deeper look / explanation please
  • Will the result of a LINQ query always be guaranteed to be in the correct order?
  • "Could not find default endpoint element that references contract"
  • Umbraco Request.QueryString is null if it's the first time the page is loaded
  • Error inconsistent accessibility method C#
  • How to program Intel Xeon Phi with C#?
  • remove nested element using regular expression
  • Is there a C# alternative to Java's vararg parameters?
  • Clear particular column values in DataTable
  • how to add event handler to programatically created checkboxes
  • Cannot apply indexing with [] to an expression of type 'System.Collections.Specialized.NameValueCollection'
  • Check for key in pre-existing dictionary in case insensitive manner
  • How to remove year from datetime object?
  • Accessing Settings in different ways
  • "This project is empty" error in Sonarqube
  • How to create reusable icon menu in Xamarin
  • Value Cannot be null in Ado.Net connectivity
  • Adding a custom/dynamic attribute when using XSD.exe
  • How to convert object to correct type
  • Automatically sign out from Forms Authentication in ASP.NET when browser is closed
  • Can a WCF service support both Buffered and Streamed transfer modes?
  • Verify a CA Certificate with a public key in C#
  • How to invoke a Web Service that requires the "patch" verb using the C# WebClient wrapper?
  • Proper way a implementing property based on generic type
  • Closing a form that is created in another thread
  • How Can You Bind a List<String> to a StackPanel
  • WPF Application Update Best Practices - Architectural Explanation
  • System.UnauthorizedAccessException in Server.MapPath()
  • Connecting and Using SQL Compact Edition in a WPF application
  • C#: weird ref in constructor to behave like "virtual field"
  • C# XDocument Load with multiple roots
  • How to decide what goes in the Domain or Application Project in a "DDD" solution?
  • How to get/set a property of an interface that is not always implemented
  • Read-only array field in unsafe struct
  • i got "Invalid attempt to call Read when reader is closed" when using sqldatareader how to solve it in a three
  • Why should I encapsulate objects in using if there is garbage collection
  • How to load Word document from byte array
  • Caliburn.Micro and ContextMenu for DataGrid Row
  • Linq "join" with a IList<T> getting "Error Unable to create a constant value.."
  • How to draw red wavy line under words in RichTextBox c# winform
  • HttpPostedFileBase returns Null MVC3
  • Refresh Dropdownlist in webform
  • How to convert serialized byte array back to its text form
  • How to do a loop to check all the variables at the same time for C#?
  • Facebook Sentiment Analysis API
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org