C# EF Core禁用懒加载时泛型方法如何按接口条件Include导航属性
EF Core 泛型服务按需加载导航属性实现问题
该问题或许已有公开解决方案,但我暂未检索到对应实现思路。
我在项目中使用EF Core,计划禁用懒加载(LazyLoading),编写可按需加载不同导航属性(NavigationProperty)的泛型方法。我定义了包含CRUD方法的服务接口,使用AutoMapper完成实体到ViewModel的映射;项目中的实体分为多类:
- 部分实体查询时无需加载导航属性
- 其余实体则需要通过
Include引入指定导航属性
我的预期是仅维护一套基础服务接口,在运行时匹配对应实现,或是在服务实现内部通过条件判断完成导航属性的按需加载逻辑,相关代码定义如下:
服务接口定义
public interface IService { Task<IEnumerable<TViewModel>> GetAsync<TEntity, TViewModel>() where TEntity : class where TViewModel : class; Task PostAsync<TEntity, TViewModel>(TViewModel model) where TEntity : class where TViewModel : class; Task<TViewModel> PatchAsync<TEntity, TViewModel>(int id) where TEntity : class; }
导航属性标记接口
public interface INavigate { int NavigationTypeId {get;set;} NavigationType NavigationType {get;set;} }
现有服务实现(无法正常运行)
public class Service { public async Task PatchAsync<TEntity, TViewModel>(Guid id, JsonPatchDocument<TViewModel> patchDoc) where TEntity : class where TViewModel : class { var query = this.dbContext.Set<TEntity>(); if(typeof(INavigate).IsAssignableFrom(typeof(TEntity))) { query = this.dbContext.Set<TEntity>() .Include(e=>e.NavigationType); // 显然这段代码无法正常工作 } var entity = await query.FirstAsync(); var viewModel = this.mapper.Map<TViewModel>(entity); patchDocument.ApplyTo(viewModel); var updatedEntity = this.mapper.Map(viewModel, entity); this.dbContext.Entry(entity).CurrentValues.SetValues(updatedEntity); this.dbContext.SaveChangesAsync(); } }
方案要求
需要可行的实现方案,满足以下约束:
- 无需为每个导航属性标记接口单独定义服务
- 无需单独添加
where TEntity : class, INavigate这类泛型约束
内容的提问来源于stack exchange,提问作者Joshit
相关产品推荐
相关产品推荐

