Tips Linq processing date, you know Linq handling of DateTime such as:? Properties, methods, support the translation of the original Linq can write the DateTime processing.
Tips Linq processing date, you know Linq handling of DateTime such as:? Properties, methods, support the translation of the original Linq can write the DateTime processing.
Testing tools: LinqPad 4.26
test environment:
- .Net Framework 4.0
- Sql Server 2008 R2 (since 2008 do not have the environment, not tried what will happen in 2008 or less)
DateTime properties such as: Date, Year, methods such as: AddDays, AddYears, will turn into the Sql, translation known method, the operation Linq To Sql or Entity Framework will be more convenient to use, where several are described below for your reference, the details look at MSDN.
1.Today or day treatment
If you want to find out today revised data, how would you under, something like that right?
where p.ModifiedDate >= DateTime.Today && p.ModifiedDate < DateTime.Today.AddDays(1)
select p
SELECT *
FROM [Product]
WHERE ([ModifiedDate] >= '2010-09-13 00:00:00.000' ) AND ([ModifiedDate] < '2010-09-14 00:00:00.000')
In fact, there's an easier way
where p.ModifiedDate.Date == DateTime.Today
select p
SELECT *
FROM [Product]
WHERE CONVERT(DATE, [ModifiedDate]) = '2010-09-13 00:00:00.000'
Is not it much simpler, of course, one day in comparison with some, such as:
where p.ModifiedDate.Date == new DateTime(2010,1,1)
select p
Tip:
DateTime.Date, is just take the time to remove the date, and DATE, is the only date of Sql Server 2008 data types.
2. Find some years of data
where p.ModifiedDate.Year == DateTime.Today.Year && p.ModifiedDate.Month == DateTime.Today.Month
select p
SELECT *
FROM [Product]
WHERE (DATEPART(Year, [ModifiedDate]) = 2010) AND (DATEPART(Month, [ModifiedDate]) = 9)
3. Add half a year out of date data
where p.ModifiedDate.AddMonths(6) >= DateTime.Today
select p
SELECT *
FROM [Product]
WHERE DATEADD(MONTH, 6, [PeriodDate]) >= '2010-09-14 00:00:00.000'
Note:
With AddHours, AddMinutes, AddSeconds, translation T-Sql, very difficult to read, but fortunately nothing usually do not bother translating the results, how long.
As AddHours (6), will be translated into
I personally think that using Linq In many cases, easy to use intuition more than T-Sql, Linq spent two years, I think my T-Sql certain degraded a lot.
Reference data
- System.DateTime 方法 (LINQ to SQL)
Original: Big Box Linq tips: Date of processing