にアクセスできません: -System.ObjectDisposedException:破棄されたオブジェクト私は、次の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;
}
}
取得し、GETALLは、私は、データベースに何かを追加しようとすると、しかし、私は「システムを取得しています、正常に動作.ObjectDisposedException:破棄されたオブジェクトにアクセスできません "エラー。
次のように私は、スタートアップの設定でリポジトリを宣言した: -
services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
問題がある可能性がありますか?私は文脈を間違って宣言していますか?
ご協力いただきありがとうございます。 await(非同期)を削除
UPDATE
は正しく
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();
}
に動作し、この正しいですか?
コンストラクタにコンテキストを渡すので、別の場所に配置されている可能性がありますか?一般的には、実行したいアトミックアクションごとにコンテキストを作成して処分する方がよいでしょう。 – juharr
私は以前のようにコンストラクタで渡す代わりに、私はすべてのメソッドで使用する必要がありますか? – Johann
新しいコンテキストがインスタンス化されているため、GetおよびAddの両方で がobvで動作しません。 – Johann