如何在表达式中获取IS NULL(从数据库中获取空值) [英] How to get IS NULL in expression (To get null values from database)

查看:95
本文介绍了如何在表达式中获取IS NULL(从数据库中获取空值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在我的应用程序中使用实体框架。考虑我有以下表结构

员工(
ID uniqueidentifier
名称 varchar 100 < span class =code-keyword> null ,
JobId uniqueidentifier null





我使用以下表达式来获取数据



表达式< Func< Employee,true>>谓词= P => p.JobId == JobIdVariable; 
** JobIdVariable 可以为空的Guid。





所以我在Employee对象Context的Where子句中使用上面的表达式。如果jobIdVariable有任何数据,那么解决方案工作正常为NULL,则查询不返回任何行。当我使用SQL分析器时,我得到以下where子句

JobId = NULL ,但在这种情况下我必须得到 JobId IS NULL 。那么如何修改我的表达式以从DB获取Null值。



感谢您的时间

解决方案

< blockquote>在where where条件的两边用0替换NULL。



类似

 Isnull(JobID, 0 )= Isnull(jobIdVariable, 0 )。





你必须根据语言要求转换上面的表达式。


经过几次尝试尝试,我找到了这个问题的解决方案。如果类型是可空类型,那么在表达式中我们使用Equals和==。



例如:在我上面的问题中,它的工作正常

表达式< func> <雇员,真>>谓语; 
if (JobIdVariable == null
{
predicate = p => p.JobId.Equals( null );
// 在这种情况下,该值必须为null且compare必须为Equals,否则通过某些与对象相关的错误。
}
else
{
predicate = p => p.JobId == JobIdVariable;
// 这里,它必须是==比较,否则会抛出一些运行时错误。
} < / func > < /跨度>


Hi,
I am using entity framework in my application. Consider I am having a following table structure

Employee(
ID uniqueidentifier,
Name varchar(100) not null,
JobId uniqueidentifier null)



I am using the following expression to get the data

Expression<Func<Employee,true>> predicate=p=>p.JobId==JobIdVariable;
**JobIdVariable is nullable Guid. 



So I am using the above expression in Where Clause of Employee object Context.Above solution works fine if jobIdVariable has any data but when it is NULL, then the query returns no rows. When I use SQL profiler, I am getting the following where clause
JobId = NULL, but in this case I have to get JobId IS NULL. So how can I modify my expression to get the Null values from DB.

Thanks for your time

解决方案

replace the NULL with 0 in both side of where condition.

something like

Isnull(JobID,0)=Isnull(jobIdVariable,0).



You would have to convert above expression as per the language requirement.


After few trial attempts, I could find the solution for this question. If the type is of nullable type, then in expression we have use both Equals and == .

Eg: In my above case in the question, its working correct when

Expression<func><employee,true>> predicate;
if(JobIdVariable==null)
{
    predicate=p=>p.JobId.Equals(null);
   //In this case, the value has to be null and compare has to be Equals else it through some Object related error.
}
else
{
    predicate=p=>p.JobId==JobIdVariable;
//Here, it has to be == comparision else some runtime error is thrown.
}</func>


这篇关于如何在表达式中获取IS NULL(从数据库中获取空值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆