根据 LINQ To SQL 查询中的位字段计算布尔值
我正在尝试对 SQL CE 数据库执行一个简单的 LINQ To SQL 查询。
var result = from item in items
where item.IsTrue == true
select item;
问题在于 IsTrue
属性是数据库中的 bit
字段(CLR 中的 bool
)。当它转到 CE 中的 SQL 时,我得到 SELECT ... WHERE ([t0].IsTrue = 1)..
1 值是 SqlCe 的整数,默认情况下不会转换它。
我在该列(IsTrue 列)上的索引没有被使用。相反,它尝试将数据库中的所有 istrue
值转换为整数,并将它们与 1 进行比较。
如何让 LINQ To SQL 生成 WHERE ([t0].IsTrue = Cast (1 位))...
?我需要以某种方式强制将该值转换为位
,从而允许使用索引?
我尝试过:
item.IsTrue == Convert.ToBoolean(1)
item.IsTrue == Convert.ToBoolean("true")
item.IsTrue == ( bool)true)
希望让表达式树在其中进行强制转换,以便将其转换为 LINQ To SQL 中的强制转换,但我似乎找不到方法。有什么想法吗?
I am trying to do a simple little LINQ To SQL query against a SQL CE database.
var result = from item in items
where item.IsTrue == true
select item;
The problem is that the IsTrue
property is a bit
field in the database (bool
in the CLR). When it goes to SQL in CE I get SELECT ... WHERE ([t0].IsTrue = 1)..
The 1 value is an integer to SqlCe and it wont cast it by default.
The index that I have on that column (the IsTrue column) doesn't get used. Instead it tries to cast all of the istrue
values in the database to integers and compares them to the 1.
How can I get LINQ To SQL to generate WHERE ([t0].IsTrue = Cast(1 as bit))...
? I need somehow to force the casting of that value to a bit
, and thereby allowing use of the index?
I tried:
item.IsTrue == Convert.ToBoolean(1)
item.IsTrue == Convert.ToBoolean("true")
item.IsTrue == (bool)true)
Hoping to get the expression tree to have a cast in it so that it converts to a cast in LINQ To SQL, but i cant seem to find a way. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我登陆此页面是因为我遇到了同样的问题。
我发现您可以通过使用编译查询来解决这个特定的问题。使用您的示例:
如果您查看生成的 SQL(通过连接
DataContext
中的日志流),由于某种原因,它会执行正确的操作,而使用非编译查询则不会。包含bool
的索引将开始工作。I landed on this page because I had the same problem.
I found you can work around this particular brokenness by using compiled queries. To use your example:
If you look at the SQL this generates (by hooking up the log stream in the
DataContext
) it for some reason does the right thing where using non-compiled queries does not. Your indices that havebool
s in them will start working.您是否尝试过省略
== true
部分并仅使用var result = from item in items where item.IsTrue select item;
或者,使用 方法语法:
var result = items.Where(item => item.IsTrue );
Have you tried leaving out the
== true
part and just usingvar result = from item in items where item.IsTrue select item;
Alternatively, using method syntax:
var result = items.Where(item => item.IsTrue);