System.ObjectDisposedException:无法访问已处置的对象

时间:2017-01-23 13:08:23

标签: c# asp.net-core-mvc dbcontext

我有以下GenericRepository: -

    public class GenericRepository<T> : IGenericRepository<T> where T : class
    {
    public readonly SportsStore2Context Context;
    protected DbSet<T> DbSet;

    public GenericRepository(SportsStore2Context context)
    {
        Context = context;
        DbSet = context.Set<T>();
    }

    public async Task<T> Get<TKey>(Expression<Func<T, bool>> filter = null, string includeProperties = "")

    {
        IQueryable<T> query = Context.Set<T>();
        query = IncludePropertiesQuery(query, includeProperties);

        if (filter != null)
        {
            query = query.Where(filter);
        }

        return await query.SingleOrDefaultAsync();
    }

    public async Task<List<T>> GetAll(Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeProperties = "")
    {
        IQueryable<T> query = Context.Set<T>();
        query = IncludePropertiesQuery(query, includeProperties);

        if (orderBy != null)
        {
            query = orderBy(query);
        }

        var collection = await query.ToListAsync();
        return collection;
    }

    public async Task Add(T entity, Expression<Func<T, bool>> filter = null)
    {
        var existing = await Get<T>(filter);

        if (existing == null)
        {
            Context.Set<T>().Add(entity);
            Save();
        }

    }


    public void Update(T entity)
    {

        Context.Set<T>().Update(entity);
        Save();
    }

    public void Delete(T entity)
    {
        var dbSet = Context.Set<T>();
        if (Context.Entry(entity).State == EntityState.Detached)
        {
            dbSet.Attach(entity);
        }
        dbSet.Remove(entity);

        Save();
    }

    private void Save()
    {
        try
        {
            Context.SaveChanges();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }

    private IQueryable<T> IncludePropertiesQuery(IQueryable<T> query, string includeProperties = "")
    {
        includeProperties = includeProperties.Trim() ?? string.Empty;
        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }

        return query;

    }

}

Get和GetAll工作正常,但是当我尝试向数据库添加内容时,我得到一个&#34; System.ObjectDisposedException:无法访问已处置的对象&#34;错误。

我在配置启动时声明了存储库: -

   services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));

可能是什么问题?我是否错误地宣布了背景?

感谢您的帮助和时间。

更新

删除await(async)确实可以正常工作

    public void Add(T entity, Expression<Func<T, bool>> filter = null)
    {
        var existing = Get<T>(filter);
        if (existing.Result != null) return;
        Context.Add(entity);
        Save();
    }

这是对的吗?

1 个答案:

答案 0 :(得分:0)

(我不知道这个特殊类,但这是混合异步和非异步代码的一般建议)

为什么建议异步函数遵循命名模式MyFuncAsync,这是有充分理由的,因为它可以让您在尝试从非异步函数调用异步函数时很容易看到。

从评论中删除此信息,这就是您调用添加

的方式
public bool Add(T entity, Expression<Func<T, bool>> filter = null)
{
    try
    {
        genericRepository.Add(entity, filter);
    }
    catch (Exception e)
    {
       return false;
    }
    return true;
}

但是你在这里从非异步函数调用异步函数(如果函数被称为AddAsync会更明显),除非你像这样阻塞非异步函数,否则会引发问题:

public bool Add(T entity, Expression<Func<T, bool>> filter = null)
{
    try
    {
        genericRepository.Add(entity, filter).Wait();
    }
    catch (Exception e)
    {
       return false;
    }
    return true;
}

如果它一直是异步的话会更好,因为这个线程会在操作完成时阻塞,但这应该可行。