"The operation could not be completed because the DbContext was deleted" # 2

I am creating a simple ASP.NET API using EF and Oracle Database. When I want to get all the items from a database table, the response (500) says "The operation could not be completed because the DbContext was deleted."

enter image description here

Well, I tried to solve this problem before posting it here. But I can not. My controller code looks like this.

 public class PruebasController : ApiController
 {

    //Prueba[] pruebas = new Prueba[] 
    //{ 
    //    new Prueba { Name = "Tomato Soup"}, 
    //    new Prueba { Name = "Yo-yo"}, 
    //    new Prueba { Name = "Hammer"} 
    //};

    public IQueryable<Prueba> GetAllPruebas()
    {
        Database.SetInitializer(new DropCreateDatabaseAlways<OracleDbContext>());

        using (var ctx = new OracleDbContext())
        {
            return ctx.Pruebas;
        }
    }
}

      

(As you can see I have a list of "pruebas" and when I return it the http service is running)

And this is my OracleDbContext

public class OracleDbContext : DbContext
{

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

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("DATA");
    }
}

      

+3


source to share


2 answers


You are returning an object IQueryable

. After you return, you exit the Using statement, which closes your Context

. You need to enumerate with .ToList()

before exiting the using statement. This will execute the request while the context is still open.

Change it like this:

public List<Prueba> GetAllPruebas()
{
   using (var ctx = new OracleDbContext())
    {
        return ctx.Pruebas.ToList();
    }
}

      



Also, you must add your initializer in the constructor of your context and not in your GetAllPruebas method, for example:

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");
    }
}

      

+3


source


The problem has been resolved. I wrote CreateDatabaseIfNotExists instead of DropCreateDatabaseAlways in Database.SetInitializer and it works.



+1


source







All Articles