如何在 EfCore 中使用原始 SQL 编写 orderBy 查询?
How to write orderBy query with raw SQL in EfCore?
我有 EfCore 查询:
return await _context.Rubrics
.AsNoTracking()
.Where(i => i.IsApproved == true)
.Include(i => i.EdDraft)
.Include(i => i.Rubric)
.ThenInclude(i => i.Title)
.Where(i => i.EdDraft.AccountId == accountId)
.OrderBy(i => i.Path)
.ToListAsync();
i.Path 是类似于“1-5-3”、“1-5-3-2”、“9-18-12”等的字符串...
我必须按字符排序 - 第一个字符,例如按“1-”、“9-”等排序
我不想用原始 sql 重写所有查询。
在 Laravel 我做:
orderBy(DB::raw(...sql))
但在 EfCore 中我找不到解决方案。
我知道如何在客户端重写 (.AsEnumerable),但我需要在服务器端编写查询。
查询必须按字符串中的第一个字符排序。
EF 核心将字符串的 Substring 方法转换为 SQL 就好了,但它需要 2 个参数重载。因此,如果我正确理解您的问题 - “如何仅按第一个字符对查询进行排序” - 使用:
return await _context.Rubrics
.AsNoTracking()
.Where(i => i.IsApproved == true)
.Include(i => i.EdDraft)
.Include(i => i.Rubric)
.ThenInclude(i => i.Title)
.Where(i => i.EdDraft.AccountId == accountId)
.OrderBy(i => i.Path.Substring(0,1))
.ToListAsync();
我有 EfCore 查询:
return await _context.Rubrics
.AsNoTracking()
.Where(i => i.IsApproved == true)
.Include(i => i.EdDraft)
.Include(i => i.Rubric)
.ThenInclude(i => i.Title)
.Where(i => i.EdDraft.AccountId == accountId)
.OrderBy(i => i.Path)
.ToListAsync();
i.Path 是类似于“1-5-3”、“1-5-3-2”、“9-18-12”等的字符串... 我必须按字符排序 - 第一个字符,例如按“1-”、“9-”等排序
我不想用原始 sql 重写所有查询。 在 Laravel 我做:
orderBy(DB::raw(...sql))
但在 EfCore 中我找不到解决方案。
我知道如何在客户端重写 (.AsEnumerable),但我需要在服务器端编写查询。
查询必须按字符串中的第一个字符排序。
EF 核心将字符串的 Substring 方法转换为 SQL 就好了,但它需要 2 个参数重载。因此,如果我正确理解您的问题 - “如何仅按第一个字符对查询进行排序” - 使用:
return await _context.Rubrics
.AsNoTracking()
.Where(i => i.IsApproved == true)
.Include(i => i.EdDraft)
.Include(i => i.Rubric)
.ThenInclude(i => i.Title)
.Where(i => i.EdDraft.AccountId == accountId)
.OrderBy(i => i.Path.Substring(0,1))
.ToListAsync();