Abp vNext 自定义 Ef Core 仓储引发异常
问题
如果将自定义仓储改为 IRepository<TEntity,TKey>
进行注入,是可以与 _courseRepostory
进行关联查询的。
我在 XXXEntityFrameworkCoreModule
的配置,以及自定义仓储 EfCoreStudentRepository
代码如下。
XXXEntityFrameworkCoreModule
代码:
public class XXXEntityFrameworkCoreModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { context.Services.AddAbpDbContext<XXXDbContext>(op => { op.AddDefaultRepositories(); }); Configure<AbpDbContextOptions>(op => op.UsePostgreSql()); } }
EfCoreStudentRepository
代码:
public class EfCoreStudentRepository : EfCoreRepository<IXXXDbContext, Student, long>, IStudentRepository { public EfCoreStudentRepository(IDbContextProvider<IXXXDbContext> dbContextProvider) : base(dbContextProvider) { } public Task<int> GetCountWithStudentlIdAsync(long studentId) { return DbSet.CountAsync(x=>x.studentId == studentId); } }
原因#
原因在异常信息已经说得十分清楚了,这里我们需要了解两个问题。
- 什么原因导致两个仓储内部的 DbContext 不一致?
- 为什么 ABP vNext 自己实现的仓储能够进行关联查询呢?
首先我们得知道,仓储内部的 DbContext
是怎么获取的。我们的自定义仓储都会继承 EfCoreRepository
,而这个仓储是实现了 IQuerable<T>
接口的,最终它会通过一个 IDbContextProvider<TDbContext>
获得一个可用的 DbContext
。
public class EfCoreRepository<TDbContext, TEntity> : RepositoryBase<TEntity>, IEfCoreRepository<TEntity> where TDbContext :