2

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

Evonet
  • 3,600
  • 4
  • 37
  • 83

1 Answers1

1

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

Evonet
  • 3,600
  • 4
  • 37
  • 83
  • 2
    That shouldn't have been the problem if you are only reading (ie: _context.Movies.Any). Typically with the repo pattern readonly DbContext is declared from the uow and you inject the uow into the repo to persist data using an internal reference. – yardpenalty.com Dec 24 '14 at 10:31