HC+EF Core项目部分字段LINQ表达式无法翻译求助
问题:Hot Chocolate + AutoMapper 过滤字段时EF Core无法翻译LINQ表达式
已直接向Hot Chocolate提交该问题,同时寻求社区帮助。
在Hot Chocolate 12 + EF Core 7项目中引入AutoMapper,参考相关问题完成配置并实现投影/过度获取功能,但过滤disabled属性时EF抛出LINQ表达式无法翻译的异常。
异常场景(过滤disabled字段)
GraphQL查询
{ sites(where: { disabled: { eq: 1 } }) { id name } }
异常信息
System.InvalidOperationException: 'The LINQ expression 'DbSet<InventSite>() .Where(i => new LazySite{ Id = Convert.ToInt32(i.SiteId), Name = i.Name } .Disabled == __p_0)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'
正常场景(过滤id/name字段)
GraphQL查询
{ sites(where: { id: { eq: 1 } }) { id name } }
生成的SQL
SELECT CONVERT(int, [i].[SiteID]) AS [Id], [i].[Name] FROM [dbo].[InventSite] AS [i] WHERE CONVERT(int, [i].[SiteID]) = @__p_0
项目配置详情
DTO类(InventSite)
public class InventSite { public string DataAreaId { get; set; } = null!; public string SiteId { get; set; } = null!; public string? Dimension4 { get; set; } public string? Name { get; set; } public int Disabled { get; set; } }
GraphQL暴露实体类(LazySite)
public class LazySite { public int Id { get; init; } public int? AxSiteId { get; init; } public string? Name { get; init; } public int Disabled { get; init; } }
AutoMapper配置
public MappingProfile() { CreateMap<InventSite, LazySite>() .ForMember(d => d.Id, e => e.MapFrom(s => Convert.ToInt32(s.SiteId))) .ForMember(d => d.AxSiteId, e => e.MapFrom(s => !string.IsNullOrWhiteSpace(s.Dimension4) ? (int?)Convert.ToInt32(s.Dimension4) : null)) //.ForMember(d => d.Disabled, e => e.MapFrom(s => s.Disabled)) .ForAllMembers(i => i.ExplicitExpansion()); }
查询代码
public class Query { [Authorize] [UseProjection] [UseFiltering] [UseSorting] public IQueryable<LazySite> GetSites([Service] ISiteService siteService, IResolverContext resolverContext) => siteService.GetSites(resolverContext); } // ISiteService方法: public IQueryable<LazySite> GetSites(IResolverContext resolverContext) => _edrHelper.GetSites().ProjectTo<InventSite, LazySite>(resolverContext); // IEdrHelper实现: public IQueryable<InventSite> GetSites() => _context.InventSites.AsNoTracking();
内容的提问来源于stack exchange,提问作者Poat
相关产品推荐
相关产品推荐

