如何模拟 linq 的 case-when?
How to emulate case-when for linq?
IQueryable a;
IQueryable b;
IQueryable res = from ab in a.Union(b)
select {
prop = ab.prop,
deletable = ab.type == CONSTANT_TYPE &&
(from d in deletableTable
where key = CONSTANT_KEY
select d).FirstOrDefault().RenderCode == CONSTANT_RENDER_CODE
};
return res;
上面的代码引发了错误
b
appears in two structurally incompatible initializations
within a single LINQ to Entities query. A type can be initialized in
two places in the same query, but only if the same properties are set
in both places and those properties are set in the same order.
我不确定是什么原因,但我想,当我 returning IQueryable 时,它无法构建 sql 字符串,因为 d in deletableTable ? true : false
.
在sql中看起来像
SELECT
case
when (SELECT TOP 1 code FROM deletable) = CONSTANT then true
else false
end
如果我想要 return IQueryable,linq 是否存在一些解决方法?
问题的错误提示是因为可查询a和可查询b中缺少deletable。
IQueryable a = getA();
IQueryable b = getB();
IQueryable res = from ab in a.Union(b)
select {
prop = ab.prop,
deletable = ab.type == CONSTANT_TYPE &&
(from d in deletableTable
where key = CONSTANT_KEY
select d).FirstOrDefault().RenderCode == CONSTANT_RENDER_CODE
};
return res;
getA
和 getB
最初返回对象 属性 prop
.
如果你想做 from ab in a.Union(b) select deletable = 12
,即使 uf 12 它在你的代码中是常量, deletable
字段应该在可查询的 a 和可查询的 b 中声明,否则你将出现错误问题。
我添加了 deletable
的声明来修复错误:
getA() {
from a ...
select new {
prop,
deletable = false //add field, to use union
}
}
getB() {
from b ...
select new {
prop,
deletable = false //add field, to use union
}
}
IQueryable a;
IQueryable b;
IQueryable res = from ab in a.Union(b)
select {
prop = ab.prop,
deletable = ab.type == CONSTANT_TYPE &&
(from d in deletableTable
where key = CONSTANT_KEY
select d).FirstOrDefault().RenderCode == CONSTANT_RENDER_CODE
};
return res;
上面的代码引发了错误
b
appears in two structurally incompatible initializations within a single LINQ to Entities query. A type can be initialized in two places in the same query, but only if the same properties are set in both places and those properties are set in the same order.
我不确定是什么原因,但我想,当我 returning IQueryable 时,它无法构建 sql 字符串,因为 d in deletableTable ? true : false
.
在sql中看起来像
SELECT
case
when (SELECT TOP 1 code FROM deletable) = CONSTANT then true
else false
end
如果我想要 return IQueryable,linq 是否存在一些解决方法?
问题的错误提示是因为可查询a和可查询b中缺少deletable。
IQueryable a = getA();
IQueryable b = getB();
IQueryable res = from ab in a.Union(b)
select {
prop = ab.prop,
deletable = ab.type == CONSTANT_TYPE &&
(from d in deletableTable
where key = CONSTANT_KEY
select d).FirstOrDefault().RenderCode == CONSTANT_RENDER_CODE
};
return res;
getA
和 getB
最初返回对象 属性 prop
.
如果你想做 from ab in a.Union(b) select deletable = 12
,即使 uf 12 它在你的代码中是常量, deletable
字段应该在可查询的 a 和可查询的 b 中声明,否则你将出现错误问题。
我添加了 deletable
的声明来修复错误:
getA() {
from a ...
select new {
prop,
deletable = false //add field, to use union
}
}
getB() {
from b ...
select new {
prop,
deletable = false //add field, to use union
}
}