我一直在尝试将LINQKit合并到共享数据访问层中,但是遇到了障碍。使用 构造嵌套查询时ExpandableQuery
,表达式解析器无法正确解包ExpandableQuery
并构造有效的 SQL 查询。抛出的错误如下:
System.NotSupportedException:无法创建“Store”类型的常量值。此上下文仅支持原始类型或枚举类型。
通过下面的示例程序,我们可以很容易地重构这个问题,并且它显然与AsExpandable()
对 `table.
class Program
{
static void Main(string[] args)
{
Database.SetInitializer<MyContext>(null);
var cs = MY_CONNECTION_STRING;
var context = new MyContext(cs);
var table = (IQueryable<Store>)context.Set<Store>();
var q = table
.AsExpandable()
.Select(t => new {Id = t.StoreId, less = table.Where(tt => tt.StoreId > t.StoreId) })
.Take(1)
.ToArray();
}
}
public class MyContext : DbContext
{
public MyContext(string connection) : base(connection) {}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Store>();
base.OnModelCreating(modelBuilder);
}
}
[Table("stores")]
public class Store
{
[Key]
public int StoreId { get; set; }
}
当您删除AsExpandable()
调用时,生成的 SQL 就是您期望执行三角连接的内容:
SELECT
[Project1].[StoreId] AS [StoreId],
[Project1].[C1] AS [C1],
[Project1].[StoreId1] AS [StoreId1]
FROM ( SELECT
[Limit1].[StoreId] AS [StoreId],
[Extent2].[StoreId] AS [StoreId1],
CASE WHEN ([Extent2].[StoreId] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
FROM (SELECT TOP (1) [c].[StoreId] AS [StoreId]
FROM [dbo].[stores] AS [c] ) AS [Limit1]
LEFT OUTER JOIN [dbo].[stores] AS [Extent2] ON [Extent2].[StoreId] > [Limit1].[StoreId]
) AS [Project1]
ORDER BY [Project1].[StoreId] ASC, [Project1].[C1] ASC
但是,当您包含 时AsExpandable()
,实体框架会将整个存储表拉入内存,然后失败并出现“无法创建常量”错误。
是否有任何已知的解决方法可以强制 LINQKitExpandableQuery
在表达式解析器中展开并评估嵌套子查询?