开发者

Error: ASP.NET: 'DataContext accessed after Dispose.'

开发者 https://www.devze.com 2023-04-13 02:54 出处:网络
There are two tables: Account (id) and BranchId(Id,Name,AccountId) and I have this code in pageload protected void Page_Load(object sender, EventArgs e)

There are two tables: Account (id) and BranchId(Id,Name,AccountId) and I have this code in pageload

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
       using (v开发者_如何学Car db = new SitesDataContext())
       {
           BranchGrid.DataSource = db.Branches.Where(b=>b.AccountId == loggedInUser.AccountId).ToList();
                    BranchGrid.DataBind();
       }
    }            
}

I understand about Linq and lazy loading and that is why I used ToList() But I was still getting error.

Now if I remove the association b/w Branch and Account, the above code works fine. However it throws exception with the association.

How can this be resolved while still keeping the association?

Thanks


Even with the ToList() your Accounts are not eagerly loaded, only the Branches

You can either:

  • remove the using {} and let the garbage collector do its job

or

  • add LoadOptions to the datacontext to eager load the Accounts with the branches (something like this)

     DataLoadOptions options = new DataLoadOptions();
     options.LoadWith<Branches>(b => b.Account);
     Context.LoadOptions = options;
    


Somewhere, the Account property of a Branch instance is being accessed. You must locate the code that is accessing that property and stop it.

0

精彩评论

暂无评论...
验证码 换一张
取 消