Linq语句和System.ObjectDisposedException错误

时间:2014-07-17 08:59:07

标签: c# linq linq-to-sql linq-to-entities

我有一个查询,它检索上下文中的一些数据。我有几个其他linq查询,它们也在同一个上下文中检索数据。然后我尝试遍历第一个查询的列表并添加第二个和第三个查询中的对象,但是稍后我在尝试访问数据时遇到异常System.ObjectDisposedException。

例如:

var model = Activator.CreateInstance<M>();
using (IContext context = ContextFactory.GetContext(DatabaseType.Live))
{
    consignmentModel = (from c in context.Consignments
                    join ct in context.Contracts on c.ContractID equals ct.ID
                    where c.ManifestID == model.Manifest.ID
                    select new ConsignmentManifestModel
                    {
                        Consignment = c,
                        Contract = ct,                        
                    }).ToList(); 

    parcels = (from p in context.Parcels
               join pp in context.ParcelProducts on p.ID equals pp.ParcelID
               join c in context.Consignments on p.ConsignmentID equals c.ID
               where c.ManifestID == model.Manifest.ID
               select p).Include("ParcelProducts").ToList();

    parcelProducts = (from pp in context.ParcelProducts
                    join p in context.Parcels on pp.ParcelID equals p.ID
                    join c in context.Consignments on p.ConsignmentID equals c.ID
                    where c.ManifestID == model.Manifest.ID
                    select pp).ToList();
    ((IObjectContextAdapter) context).ObjectContext.ContextOptions.LazyLoadingEnabled = false;
    foreach(var c in consignmentModel)
    {
        var consignment = c.Consignment;
        consignment.SiteOrder = c.SiteOrder;
        consignment.Contract = c.Contract;
        foreach (var p in parcels)
        {
             if (p.ConsignmentID == consignment.ID)
             {                                                        
                  foreach (var pp in parcelProducts)
                  {                                                               
                      if (pp.ParcelID == p.ID) p.ParcelProducts.Add(pp);
                  }
                  consignment.Parcels.Add(p);
             }
        }
        model.Consignments.Add(consignment);
    }
    ((IObjectContextAdapter) context).ObjectContext.ContextOptions.LazyLoadingEnabled = true;
}

:
:
:

foreach (var consignment in model.Consignments)
{
     foreach (var parcel in consignment.Parcels)  // ERROR - System.ObjectDisposedException

0 个答案:

没有答案