Repository error - The context cannot be used while the model is being created

asp.net-mvc c# entity-framework

Question

I'm getting the following exception when trying to retrieve data from my registry:

An exception of type 'System.InvalidOperationException' occurred in OHR.Repository.dll but was not handled in user code

Additional information: The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.

This error occurs on the first database query that I'm running in the method called MovieExists:

MovieRepository.cs:

private readonly ApplicationDbContext _context;

public MovieRepository(ApplicationDbContext context)
{
    this._context = context;
}

public bool MovieExists(string MovieUrl)
{

    try
    {
        bool result;
        using (_context)
        {
            // The next line causes the exception
            result = _context.Movies.Any(p => p.Url == MovieUrl);
        }
        return result;
    }
    catch (Exception e)
    {
        throw;
    }
}

My context.cs

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }

    public virtual DbSet<Movie> Movies { get; set; }

}

I'm using EF6, and while I have async EF tasks, this very first one is not using any async calls so I don't think I'm trying to use the context on multiple threads.

I assume I'm not instantiating the context properly, but can't see how to fix the problem.

Thanks

1
2
8/16/2014 4:21:52 AM

Accepted Answer

Fixed, the problem was that I made the ApplicationDbContext _context readonly. Removing readonly fixed the issue.

1
8/16/2014 11:18:41 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow