您的位置:首页 > 数据库

LINQ to SQL语句(14)之Null语义和DateTime

2012-12-14 15:03 309 查看


Null语义

说明:下面第一个例子说明查询ReportsToEmployee为null的雇员。第二个例子使用Nullable<T>.HasValue查询雇员,其结果与第一个例子相同。在第三个例子中,使用Nullable<T>.Value来返回ReportsToEmployee不为null的雇员的ReportsTo的值。


1.Null

查找不隶属于另一个雇员的所有雇员:
var q =
from e in db.Employees
where e.ReportsToEmployee == null
select e;


2.Nullable<T>.HasValue

查找不隶属于另一个雇员的所有雇员:
var q =
from e in db.Employees
where !e.ReportsTo.HasValue
select e;


3.Nullable<T>.Value

返回前者的EmployeeID 编号。请注意.Value 为可选:
var q =
from e in db.Employees
where e.ReportsTo.HasValue
select new
{
e.FirstName,
e.LastName,
ReportsTo = e.ReportsTo.Value
};


日期函数

LINQ to SQL支持以下DateTime方法。但是,SQL Server和CLR的DateTime类型在范围和计时周期精度上不同,如下表。
类型
最小值
最大值
计时周期
System.DateTime
0001 年 1 月 1 日
9999 年 12 月 31 日
100 毫微秒(0.0000001 秒)
T-SQL DateTime
1753 年 1 月 1 日
9999 年 12 月 31 日
3.33… 毫秒(0.0033333 秒)
T-SQL SmallDateTime
1900 年 1 月 1 日
2079 年 6 月 6 日
1 分钟(60 秒)
CLR DateTime 类型与SQL Server类型相比,前者范围更大、精度更高。因此来自SQL Server的数据用CLR类型表示时,绝不会损失量值或精度。但如果反过来的话,则范围可能会减小,精度可能会降低;SQL Server日期不存在TimeZone概念,而在CLR中支持这个功能。

我们在LINQ to SQL查询使用以当地时间、UTC 或固定时间要自己执行转换。

下面用三个实例说明一下。


1.DateTime.Year

var q =
from o in db.Orders
where o.OrderDate.Value.Year == 1997
select o;


语句描述:这个例子使用DateTime 的Year 属性查找1997 年下的订单。


2.DateTime.Month

var q =
from o in db.Orders
where o.OrderDate.Value.Month == 12
select o;


语句描述:这个例子使用DateTime的Month属性查找十二月下的订单。


3.DateTime.Day

var q =
from o in db.Orders
where o.OrderDate.Value.Day == 31
select o;


语句描述:这个例子使用DateTime的Day属性查找某月 31 日下的订单。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: