注入泛型仓储后EF Core中Include方法失效问题排查与解决
EF Core泛型仓储中.Include加载关联对象为null的问题解决
问题背景
我一直采用「创建DB上下文 + 实现泛型仓储」的模式开发,泛型仓储实现代码如下:
public class GenericRepository<T> : IGenericRepository<T> where T : BaseDomain { private readonly FitnessAppContext _dbContext; public GenericRepository(FitnessAppContext dbContext) { _dbContext = dbContext; } public async Task Create(T entity) { await _dbContext.AddAsync(entity); _dbContext.SaveChanges(); } public async Task Delete(Guid id) { _dbContext.Set<T>().FirstOrDefault(a => a.Id.Equals(id)).Delete(); _dbContext.SaveChanges(); } public IQueryable<T> GetAll() { return _dbContext.Set<T>().Where(a => a.IsDeleted.Equals(false)).AsQueryable(); } public async Task<T> GetById(Guid id) { var entity = await _dbContext.Set<T>().FirstOrDefaultAsync(a => a.Id.Equals(id) && a.IsDeleted.Equals(false)); return entity; } public async Task Update(T entity) { _dbContext.Set<T>().Update(entity); await _dbContext.SaveChangesAsync(); } public async Task<DbSet<T>> GetSet() { return _dbContext.Set<T>(); } public IQueryable<T> GetByFilter(Expression<Func<T, bool>> predicate) { return _dbContext.Set<T>().Where(predicate).AsQueryable().Where(a=>a.IsDeleted.Equals(false)).AsQueryable(); } public async Task ModifyAndSave() { await _dbContext.SaveChangesAsync(); } }
依赖注入的代码如下:
private readonly IGenericRepository<Customer> _customerGenericRepository; private readonly IGenericRepository<Training> _trainingGenericRepository; public FitnessAppQuery(IGenericRepository<Customer> customerGenericRepository, IGenericRepository<Training> trainingGenericRepository) { _customerGenericRepository = customerGenericRepository; _trainingGenericRepository = trainingGenericRepository; }
Program.cs中的服务注册配置:
builder.Services.AddDbContext<FitnessAppContext>(); builder.Services.AddTransient<ITrainingService, TrainingService>(); builder.Services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>)); builder.Services.AddScoped<IFitnessAppQuery, FitnessAppQuery>(); builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
遇到的问题
在业务逻辑层调用仓储的GetSet()方法,尝试通过.Include()加载关联对象TrainingType时,主数据能正常获取,但关联对象始终为null:
public async Task<ListTrainingOutputModel> ListAllTraining() { var outputModel = new ListTrainingOutputModel(); var trainingSet = await _trainingGenericRepository.GetSet(); var trainingswithincluded = trainingSet.Include(a => a.TrainingType).ToList(); try { outputModel.IsSuccess = true; outputModel.StatusMessage = "Trainings listed successfully"; return outputModel; } catch (Exception ex) { outputModel.Data = null; outputModel.IsSuccess = false; outputModel.StatusMessage = ex.ToString(); return outputModel; } }
查阅大量文档和工具后仍未解决,最终定位到问题根源。
解决方法
问题出在Include方法的命名空间引用错误:我误用了Microsoft.System.Data中的Include()方法,而EF Core中用于加载关联对象的正确方法来自Microsoft.EntityFrameworkCore命名空间。替换引用的命名空间后,关联对象正常加载,问题解决。
内容的提问来源于stack exchange,提问作者gokaydinc
相关产品推荐
相关产品推荐

