简体   繁体   中英

C# / EntityFramework - Accessing and entity is raising System.ObjectDisposedException

I am fairly new EntityFramework so I hope I am going about this in the correct way.

I have a DbContext class:

public class UsersDbContext : DbContext
{
    public DbSet<DbUsersModel> Users { get; set; }
    public DbSet<DbApplicationsModel> Applications { get; set; }
    public DbSet<DbImageModel> Images { get; set; }
}

This is for a code-first database that has the structure: Each DbUsersModel has multiple DbApplicationsModel elements, and each DbApplicationsModel has multiple DbImageModel elements.

Given an DbImageModel.ImageTag , I would like to obtain in the DbApplicationsModel that it belongs to.

I can easily grab the DbImageModel information based on the DbImageModel.ImageTag property using the code:

using (UsersDbContext ctx = new UsersDbContext())
{
    DbImageModel image = ctx.Images.FirstOrDefault(s => s.ImageTag == imageTag);
    if (image != null)
    {
        return image;
    }
}

This returns an instance of DbImageModel correctly, however, in the parent class (where image is returned to), I cannot access image.Applications because the System.ObjectDisposedException exception is fired, presumably because I'm trying to access image.Applications outside the using .

Is there any way force the context to get image.Applications inside the using and retain it so that the information can be accessed outside the using code?

Yes, instead of lazy-loading applications do eager loading (by including related entities into resultset):

using (UsersDbContext ctx = new UsersDbContext())
{
    DbImageModel image = ctx.Images.Include(i => i.Applications)
                            .FirstOrDefault(s => s.ImageTag == imageTag);
    if (image != null)        
        return image;        
}

With lazy-loading EF returns proxy classes which hold reference to DbContext . This reference is used when you are trying to get related entities later. If context is disposed at that time, you see ObjectDisposedException .

Eager loading loads related entities at same time when main entity is loaded.

Suggested reading: Loading Related Entities with Entity Framework

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM