'There is already an open DataReader associated with this Connection which must be closed first c#
Good day! Error occurs by using Repository and UnitOfWork pattern (I am trying to add object to the database). By calling DatabaseContext without patterns is all okay.
There is Unit Of Work :
public class UnitOfWork : IUnitOfWork, IDisposable
{
private IRepository<User> _userRepository;
private readonly DatabaseContext context;
public UnitOfWork(DatabaseContext _context)
{
context = _context;
}
public IRepository<User> UserRepository
{
get
{
if (_userRepository == null)
{
_userRepository = new Repository<User>(context);
}
return _userRepository;
}
}
async Task<int> IUnitOfWork.SaveChangesAsync() => await context.SaveChangesAsync();
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
There is a method of adding to the database (Repository) :
public async Task InsertAsync(TEntity entity)
{
await dbSet.AddAsync(entity);
}
System.InvalidOperationException: "There is already an open DataReader associated with this Connection which must be closed first."
Error occurs on the line of saving changes by disposing (code of Dispose is upper)
await _unitOfWork.SaveChangesAsync();
The simple method of saving :
async Task<int> IUnitOfWork.SaveChangesAsync() => await context.SaveChangesAsync();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
