存储库错误——在创建模型时不能使用上下文

时间:2022-12-22 21:04:00

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

类型系统的一个例外。发生在OHR.Repository InvalidOperationException”。但是在用户代码中没有处理dll

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.

附加信息:在创建模型时不能使用上下文。如果在onmodelcreation方法中使用上下文,或者同一上下文实例被多个线程同时访问,则可能引发此异常。注意,DbContext和相关类的实例成员不能保证是线程安全的。

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

这个错误发生在我在MovieExists方法中运行的第一个数据库查询:

MovieRepository.cs:

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

我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.

我使用的是EF6,虽然我有异步EF任务,但是第一个任务没有使用任何异步调用,所以我不认为我试图在多个线程上使用上下文。

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

我假设我没有恰当地实例化上下文,但是我不知道如何修复这个问题。

Thanks

谢谢

1 个解决方案

#1


1  

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

修正的问题是,我只读取ApplicationDbContext _context _context。删除readonly修复了问题。

#1


1  

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

修正的问题是,我只读取ApplicationDbContext _context _context。删除readonly修复了问题。