我遵循ASP.NET Core中的通用存储库模式,但在IRepository
上,我使用IQueryable
而不是IEnumerable
:
public interface IRepository<T> where T: BaseEntity
{
IQueryable<T> Table { get; }
IEnumerable<T> TableNoTracking { get; }
T Get(long id);
void Insert(T entity);
void Update(T entity);
void Delete(T entity);
}
以及实现类:
public class EFRepository<T> : IRepository<T> where T : BaseEntity
{
private readonly ApplicationDbContext _ctx;
private DbSet<T> entities;
string errorMessage = string.Empty;
public EFRepository(ApplicationDbContext context)
{
this._ctx = context;
entities = context.Set<T>();
}
public virtual IQueryable<T> Table => this.entities;
}
服务类:
public class MovieService : IMovieService
{
private readonly IRepository<MovieItem> _repoMovie;
public MovieService(IRepository<MovieItem> repoMovie)
{
_repoMovie = repoMovie;
}
public async Task<PaginatedList<MovieItem>> GetAllMovies(int pageIndex = 0, int pageSize = int.MaxValue,
IEnumerable<int> categoryIds = null)
{
var query = _repoMovie.Table;
if (categoryIds != null)
{
query = from m in query
where categoryIds.Contains(m.CategoryId)
select m;
}
return await PaginatedList<MovieItem>.CreateAsync(query, pageIndex, pageSize);
}
}
在 Startup.cs 中:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc();
services.AddScoped(typeof(IRepository<>), typeof(EFRepository<>));
services.AddTransient<IMovieService, MovieService>();
services.AddTransient<ICategoryService, CategoryService>();
}
这段代码会抛出一个错误:
InvalidOperationException: 在前一个操作完成之前,此上下文启动了第二个操作。任何实例成员都不能保证是线程安全的。
如果我将 IRepository
切换回 IEnumerable
,那么它就可以正常运行。
有没有办法让它使用 IQueryable
正确地运行EF Core?
query = from m in query
where categoryIds.Contains(m.CategoryId)
select m;