今天遇到一个问题,怎么在where里判断一个字段是否为null,并且这个字段不是字符串string类型,而是int和GUID类型,折腾了半天终于搞明白了。(由于项目是我半路接手的,问题是前期的同事给我挖了一个坑,我今天就是填坑的)

1.在说这个问题之前,我先说一下数据库的表与C#之间model的对应:

一般数据库中的表我们都可以使用代码生成器(东软代码生成器)生成,其中字段的可空不可空也会给我们生成,如:表

用代码生成器生成的model是:

/// <summary>
/// SettingConfiguration:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[Serializable]
public partial class SettingConfiguration
{
public SettingConfiguration()
{}
#region Model
private int _id;
private string _name;
private string _value;
private int? _parentid;
/// <summary>
///
/// </summary>
public int Id
{
set{ _id=value;}
get{return _id;}
}
/// <summary>
///
/// </summary>
public string Name
{
set{ _name=value;}
get{return _name;}
}
/// <summary>
///
/// </summary>
public string Value
{
set{ _value=value;}
get{return _value;}
}
/// <summary>
///
/// </summary>
public int? ParentId
{
set{ _parentid=value;}
get{return _parentid;}
}
#endregion Model }

数据库中我们可以看到ParentId这个字段是可以为空的,其他字段不能为空;

对应到代码生成器生成的代码Model就可以看到代码:

public int? ParentId

{
set{ _parentid=value;}
get{return _parentid;}
}

主要是int?

有些能不知道这个int?是什么意思?和int有什么区别?这里简单说一下两者之间的区别:int?是可以为null的,而int是不能赋值null的:如下面两个代码:

int? a = null; //编译成功
int a = null; //编译错误。
int?允许把null赋值给数值型,这个是为了兼容SQL或者其它数据库中Null这个空值所设定的。

所以:在把数据库的表转化成model时,一定要把可为空的字段转化成对应的可为空的C#字段:

主要有

int——>int?

Guid——>Guid?

DateTime——>DateTime?

short——>short?

decimal——>decimal?

注意:有人说string为什么不转化成string?  额额额额~~~~~你傻呀,string类型的字段本来就可以为null,何必要写出string?,多此一举。

通过上面的介绍,大家一定对数据库表转化成model有了一定的了解。那么我们就言归正传,说问题:

2.问题的根源

问题的根源就是同是在建model的时候,该转化的没转化,导致我查询一而再、再而三的失败。

对于可以为null的字段,如果要判断这个字段是不是null,比如我们在查询表SettingConfiguration中ParentId是null的数据,我们就可以这样写:

var dtvar = (from des in db.SettingConfiguration
                 where(des.ParentId==null)
      select des);

这样查询肯定没问题的,可以~~~~嘿嘿嘿嘿嘿嘿~~~

如果你在建model的时候ParentId的字段是

public int ParentId

{
set{ _parentid=value;}
get{return _parentid;}
}

这样写的,那你怎也查不到数据,并且还不会报错,让你郁闷终生(我就是这么郁闷的),郁闷郁闷,在网上找了很多方法,都不能查询出数据,

后来改了一下model之后,什么问题都解决了,这就是一个大坑,让我填平了,同时在提醒大家,建model一定要和数据库对应,要不然以后坑的都是自己。

下面提供一些很有用的查询null的方法:

LINQ TO SQL   Null 查询

方法一:

from o in Orders  where o.ShippedDate==null  select o

对应的Lamda表达式为:

Orders .Where (o => (o.ShippedDate == (DateTime?)null))

对应的SQL语句为:

方法二:

from o in Orders  where Nullable<DateTime>.Equals(o.ShippedDate,null)  select o

对应的Lamda表达式为:

Orders .Where (o => Object.Equals (o.ShippedDate, null))

对应的SQL语句为:

方法三:

from o in Orders  where !o.ShippedDate.HasValue  select o

对应的Lamda表达式为:

Orders .Where (o => !(o.ShippedDate.HasValue))

对应的SQL语句为:

方法四:

from o in Orders  where o.ShippedDate.Value==(DateTime?)null  select o

对应的Lamda表达式为:

Orders.Where (o => ((DateTime?)(o.ShippedDate.Value) == (DateTime?)null))

 对应的SQL语句为:

SELECT [t0].[OrderID], [t0].[CustomerID], [t0].[EmployeeID], [t0].[OrderDate], [t0].[RequiredDate], [t0].[ShippedDate], [t0].[ShipVia], [t0].[Freight], [t0].[ShipName], [t0].[ShipAddress], [t0].[ShipCity], [t0].[ShipRegion], [t0].[ShipPostalCode], [t0].[ShipCountry]  FROM [Orders] AS [t0]  WHERE ([t0].[ShippedDate]) IS NULL

方法五:

from o in Orders  where  System.Data.Linq.SqlClient.SqlMethods.Equals(o.ShippedDate.Value,null)  select o

对应的Lamda表达式为:

Orders .Where (o => Object.Equals (o.ShippedDate.Value, null))

对应的SQL语句为:

这五种方法,都是可以借鉴的。

Linq里where出现null的问题的更多相关文章

  1. linq查询数值为null的问题以及数据表的关联计算问题

    说明:下面实例都是我进行项目开发时的真实部分代码,毫无保留 一.数据表的关联计算 //把当前年度的分差计算出来,建立两个关联的数据表 try { using(TransactionScope scop ...

  2. Linq sum()时遇到NULL

    当使用linq求和sum()时,如果某列数据为null,就会出现异常 使用下面的语句即可解决相关问题: db.TableModel.Where(w => w.ID == ID).Select(s ...

  3. linq里的select和selectmany操作

    Select() 和 SelectMany() 的工作都是依据源值生成一个或多个结果值.Select() 为每个源值生成一个结果值.因此,总体结果是一个与源集合具有相同元素数目的集合.与之相反,Sel ...

  4. sql里条件is null 在thinkphp里

    $map['字段名'] = array('exp',' is NULL'); 譬如:$condition['url']  = array('exp',' is NULL');

  5. LINQ里的Distinct()

    IQueryable 继承自IEnumerable 先举例: #region linq to object List<People> peopleList = new List<Pe ...

  6. shell里的/dev/null 2>&1详解

    shell中可能经常能看到: >/dev/null 2>&1 命令意思是:标准输出stdout 和标准错误输出stderr 也重定向到空设备文件,即不显示输出信息 分解这个组合:“ ...

  7. linq里lambda写的join查询,并附加动态拼接的条件,条件为enum类型的查询

    因为查询条件不固定的原因,sql式的linq查询没法动态拼接条件. 网上搜的资料整理之后终于解决. 参考资料: enum使用 http://blog.csdn.net/slowlifes/articl ...

  8. linq里的select和selectmany操作 投影运算

    原文地址:https://msdn.microsoft.com/zh-cn/library/bb546168.aspx#Mtps_DropDownFilterText 投影运算   其他版本   投影 ...

  9. LINQ里的“equals”和“==”的区别

    对于值类型,如果对象的值相等,则相等运算符 (==) 返回 true,否则返回 false.对于string 以外的引用类型,如果两个对象引用同一个对象,则 == 返回 true.对于 string ...

随机推荐

  1. BZOJ4300_绝世好题_KEY

    题目传送门 刚开始是看到这道题目还以为是序列连续的. 当然了,序列可以不连续. 设f[i]表示到第i位时的序列的最长长度. 取cnt=Max f[j]+1,然后转移回去使f[j]=cnt. 这是为了让 ...

  2. Linux下安装Nginx并实现socket代理

    nginx可以使用各平台的默认包来安装,本文是介绍使用源码编译安装,包括具体的编译参数信息. 正式开始前,编译环境gcc g++ 开发库之类的需要提前装好,这里默认你已经装好. ububtu平台编译环 ...

  3. mysql中的直方图采样逻辑

    int handler::sample_next(uchar *buf) { // Temporary set inited to RND, since we are calling rnd_next ...

  4. Java: Replace a string from multiple replaced strings to multiple substitutes

    Provide helper methods to replace a string from multiple replaced strings to multiple substitutes im ...

  5. 结合BeautifulSoup和hackhttp的爬虫实例

    网页页数的改变 headers头不添加

  6. 安装mysql-5.7.12-winx64

    之前安装mysql时未做总结,换新电脑,补上安装记录,安装的时候,找了些网友的安装记录,发现好多坑 1.mysql-5.7.12-winx64.zip下载 官方下载地址:http://dev.mysq ...

  7. 关于Python3中函数:

    # 关于Python3中函数: - 定义 定义函数使用关键字def,后接函数名和放在圆括号()中的可选参数列表,函数内容以冒号起始并且缩进.一般格式如下:``` def 函数名(参数列表): &quo ...

  8. hadoop3.0新特性及新功能

    Hadoop-3.0.0-alpha2版本发布,相比之前的hadoop-2.x有一系列的功能增强.但目前还是个alpha版本,有很多bug,且不能保证API的稳定和质量. 主要变化 Java最低版本要 ...

  9. Machine Learning分类:监督/无监督学习

    从宏观方面,机器学习可以从不同角度来分类 是否在人类的干预/监督下训练.(supervised,unsupervised,semisupervised 以及 Reinforcement Learnin ...

  10. POJ 1639 Picnic Planning(最小度限制生成树)

    Description The Contortion Brothers are a famous set of circus clowns, known worldwide for their inc ...