www1986
www1986

Reputation: 101

Entity Framework lazy loading in using statement

I am so curious, when I went to deep into Entity Framework and will be glad to help me understand about lazy loading in this example which I show here:

public partial class Customer
{
    public int CustomerID { get; set; }
    public Nullable<int> PersonID { get; set; }
    public Nullable<int> StoreID { get; set; }
    public Nullable<int> TerritoryID { get; set; }
    public string AccountNumber { get; set; }
    public System.DateTime ModifiedDate { get; set; }

    public virtual Territory Territory { get; set; }
}

public partial class Territory
{
    public Territory()
    {
        this.Customers = new HashSet<Customer>();
    }

    public int TerritoryID { get; set; }
    public string Name { get; set; }
    public string CountryRegionCode { get; set; }
    public string C_Group_ { get; set; }
    public decimal SalesYTD { get; set; }
    public decimal SalesLastYear { get; set; }

    public virtual ICollection<Customer> Customers { get; set; }
}


public ActionResult LoadData()
{
    var draw = Request.Form.GetValues("draw").FirstOrDefault();
    var start = Request.Form.GetValues("start").FirstOrDefault();
    var length = Request.Form.GetValues("length").FirstOrDefault();

    var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
    var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();

    var pageSize = length != null ? Convert.ToInt32(length) : 0;
    var skip = start != null ? Convert.ToInt32(start) : 0;
    int totalRecords = 0;

    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {           
        //1.
        var items = dc.Customers.Select(a => a);

        //2. 
        //var items = dc.Customers.Select(a => new
        //{
        //    a.CustomerID,
        //    a.PersonID,
        //    a.StoreID,
        //    TerritoryName = a.Territory.Name,
        //    a.AccountNumber,
        //    a.ModifiedDate
        //});

        if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
        {
            items = items.OrderBy(sortColumn + " " + sortColumnDir);
        }

        totalRecords = items.Count();
        var data = items.Skip(skip).Take(pageSize).ToList();

        return Json(new { recordsFiltered = totalRecords, recordsToral = totalRecords, data = data }, JsonRequestBehavior.AllowGet);
    }
}

I've numbered some parts. In first case as you see I select all customers, lazy loading is true and this throws an error:

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

If I uncomment the second part, it will work without errors. The only difference between them is that in second case I select columns which I need

Upvotes: 1

Views: 472

Answers (1)

Guru Stron
Guru Stron

Reputation: 141895

This is because JsonResult(from return Json(...) statement) will be executed by ASP after the using block is left and it will try to serialize all fields of your Customer object and will try to reach Territory reference property after your dbcontext has been disposed.

Upvotes: 2

Related Questions