开发者

Linq to Sql issue with Long DateTime

Problem: Sql dateTime column which contains legacy data that has time constraints against it. I have an MVC form with Date selector to allow users to select a date and bring all records back from DB that has that date.

Issue I have however is that the linq to sql is literal to the data model and I cannot cast the datetime colum to date only for the comparison. heres a code snippet

myDateSelected = 27/01/2011

p.PostedDate in database would equal something like 27/01/2001 17:09:00

var p from products
where p.PostedDate == myDateSelected
select p

How can I cast p.PostedDate to strip the time element off to allow for the compare to开发者_高级运维 work?

pretty new to Linq and so far cannot find solution to my problem.


I am assuming that p.PostedDate is a DateTime object. If that is true, this should do it.

var p from products
where p.PostedDate.Date == myDateSelected
select p


You can call DateTime.Date to truncate the time element, and LINQ-to-SQL will translate that to SQL for you:

var p from products
where p.PostedDate.Date == myDateSelected
select p

will get translated to something like this:

-- Region Parameters
DECLARE @p0 DateTime = '2010-02-24 00:00:00.000'
-- EndRegion
SELECT [t0].[PostedDate]
FROM [Products] AS [t0]
WHERE CONVERT(DATE, [t0].[PostedDate]) = @p0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜