【发布时间】:2017-04-15 09:59:21
【问题描述】:
我关注Generic Repository Pattern in 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;
【问题讨论】:
-
我猜可能是 services.AddScoped(typeof(IRepository), typeof(EFRepository));和 services.AddTransient
();这将调用另一个 ef 上下文。如果我只是删除服务类并直接使用Repository,那就可以了。
标签: c# asp.net-mvc entity-framework