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
Select(a => a)
in the first case. – Guru Stron Aug 31 '16 at 10:43items.OrderBy
here? OrderBy doesn't take a string as a parameter, it takes a func or more usually an expression. – DavidG Aug 31 '16 at 10:51