-1

I would to make an ASP.NET MVC API with data from my database. To do this I use LINQ. I create my context and get all tariffs where delete is false.

[HttpGet]
public JsonResult Index()
{
    List<Tariff> temp = new List<Tariff>();
    using (Context context = new Context())
    {
        temp = context.Tariff.Where(t => !t.Delete).ToList<Tariff>();
    }
    return Json(temp, JsonRequestBehavior.AllowGet);
}

When I debug, temp contains a List of System.Data.Entity.DynamicProxies.Tariff_... instead of MyNamespace.Models.Tariff. When I continue it gives me this exception:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

What I'm doing wrong?

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
  • 4
    You probably have lazy loading enabled and the associated collections on type `Tariff` are being enumerated during serialization. As serialization occurs after the `Context` instance has been disposed the Exception is thrown – Igor Nov 03 '17 at 09:07
  • @Igor: how can I disable that? – H. Pauwelyn Nov 03 '17 at 09:09
  • 3
    `DbContext.Configuration.LazyLoadingEnabled = false;` – Igor Nov 03 '17 at 09:11
  • 1
    or place the return statement inside the `using` scope. As long you do not return Task – Frank Nielsen Nov 03 '17 at 09:22

1 Answers1

1

Disbale the lazy loading for the DB context:

context.Configuration.LazyLoadingEnabled = false;

If you need to do it for this query. And if you want it globally in the application, then in your ObjectContext constructor:

public DbContext() : base("name=DbContext", "DbContext")
{
    this.Configuration.LazyLoadingEnabled = false;
    OnContextCreated();
}
alaa_sayegh
  • 2,141
  • 4
  • 21
  • 37