EF Core 7中Guid的CompareTo方法无法被LINQ查询转换的问题求助
我在EF 6中使用以下LINQ查询(主键PK为Guid类型)时可正常运行:
var partialSCs = repository.MyClass .Where(x => x.PK.CompareTo(pk) > 0) .OrderBy(x => x.PK) .Take(10);
该LINQ查询可成功转换为SQL查询。但升级至EF Core 7后,出现如下错误:
'The LINQ expression 'DbSet()
.Where(s.PK.CompareTo((object)__pk_2) > 0)'
could not be translated. Additional information: Translation of method 'System.Guid.CompareTo' failed.
If this method can be mapped to your custom function, refer to relevant documentation for more information.
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'. Refer to relevant documentation for more
information.'
我已查阅两篇相关StackOverflow文章,文中称CompareTo方法应当可用,但我的情况并非如此,特此求助。
解决方案
EF Core对Guid的CompareTo方法翻译支持存在版本差异或场景限制,你可以直接用关系运算符替代CompareTo,因为Guid在EF Core中可以直接进行大于/小于比较,改写后的查询如下:
var partialSCs = repository.MyClass .Where(x => x.PK > pk) .OrderBy(x => x.PK) .Take(10);
如果必须使用CompareTo,可以通过自定义函数映射来实现,但上述关系运算符的写法更简洁高效,是官方推荐的替代方案。
内容的提问来源于stack exchange,提问作者elahehab

