c# - 在 Where 子句上的 ServiceStack ORMLite JoinAlias
问题描述
我正在尝试将 Where 子句添加到使用 JoinAlias 连接的表中,但似乎没有办法在 where 子句上指定 JoinAlias。
我正在尝试多次加入同一个表,然后根据用户输入将可变数量的 where 子句添加到连接中:
var userFilterList = new List<Expression<Func<LocationDb, LocationAttributesDateTimeDb, bool>>>();
Expression <Func<LocationDb, LocationAttributesDateTimeDb, bool>> joinPredicate = (loc, ext) =>
loc.LocationId == ext.LocationId && ext.AttributeId == attributeId;
query = query.Join<LocationAttributesDateTimeDb>(joinPredicate, ctx.JoinAlias($"ext{attributeId}"));
foreach (var item in userFilterList)
{
query = query.Where<LocationDb, LocationAttributesDateTimeDb>(item);
}
主要问题是,似乎没有办法将 JoinAlias 添加到 Where 子句中。如果我尝试按原样运行查询,则会收到有关缺少别名的异常。
如果我尝试下面的代码,我会得到一个编译异常:
query = query.Where<LocationDb, LocationAttributesDateTimeDb>(item, ctx.JoinAlias($"ext{attributeId}"));
有没有办法将 JoinAlias 添加到 where 子句,而无需将 Where 子句编写为手动 SQL?
或者,是否可以使用另一种方法将多个请求拼接到单个 Join 谓词中?
解决方案
请注意,在MyGet 上的最新 v5.4.1 预发行版中, JoinAlias()
已弃用并取而代之的是,TableAlias()
它使用不同的实现来替换别名,同时遍历表达式树,同时生成 SQL 语句,而JoinAlias()
通过在生成的 SQL 上进行后字符串替换来工作,这更多脆弱的。
WHERE 语句中没有TableAlias()
,因为无法确定应在何处使用别名,下面是一些如何在 WHERE条件下使用 TableAlias 的示例:
q.Where<Team, Teamuser>((t, u) => t.Id == Sql.TableAlias(u.TeamId, "Leader"));
q.Where<Teamuser>(u => Sql.TableAlias(u.Id, "Leader") == 1);
q.Where<Team, Teamuser>((t, u) => Sql.TableAlias(t.Id, q.DialectProvider.GetQuotedTableName(ModelDefinition<Team>.Definition)) == Sql.TableAlias(u.TeamId, "Leader")); // Workaround, but only works for fields, not constants
q.Where<Team, Teamuser>((user, leader) => Sql.TableAlias(user.Id, "Teamuser") < Sql.TableAlias(leader.Id, "Leader"));
推荐阅读
- android - RecyclerView 的 ViewHolders 变得不可点击
- typescript - 如何使用严格布尔表达式检查错误或未定义?
- javascript - 从 URL 到排序数组 ReactJS 的 JSON
- c# - 如何使用代理设置 C# 获取 Msgraph 令牌
- jupyter - 如何检查代码是否在 voila 或 jupyter 中运行
- r - x 二元运算符的非数字参数
- python - Python 正则表达式替代
- javascript - 贝宝结帐按钮
- oracle - 在 oracle 中的情况下缺少关键字错误
- mocha.js - Mocha:以并行和串行模式运行测试