3

In LINQ to SQL, how do I compare only the date part of an sql datetime column and .net datetime object?


5 답변


3

Try using the Date property of both:

Date today = DateTime.Today; // Effectively DateTime.Now.Date

var dataFromToday = from record in context.Records
                    where record.TimeStamp.Date == today
                    select record;

I believe this works for LINQ to SQL... as tvanfosson says, it doesn't for EF.


  • I know that it doesn't. That bit me yesterday. - tvanfosson
  • @tvanfosson: Duly made more emphatic :) - Jon Skeet
  • A real pain, too, since I typically mock out the data context for unit tests and it does work with LINQ to objects (obviously). I have to remember that when developing the repository that the unit tests can lie about stuff like that. - tvanfosson

1

Linq to SQL supports translation of the Date property to SQL for comparisons, etc. More information on the supported options can be found on MSDN.


0

You could create a CLR UDF to do the date only compare and then reference that in your linq to sql linq query.


0

using System.Data.Entity;

DbFunctions.TruncateTime(u.BirthDate) = DbFunctions.TruncateTime(someDate)


0

using System.Data.Objects.SqlClient; //Don't forget this!!

//You can access to SQL DatePart function using something like this:

YourTable.Select(t => new { DayOfWeek = SqlFunctions.DatePart("weekday", t.dateTimeField) - 1 }); //Zero based in SQL

//You can compare to SQL DatePart function using something like this:

DateTime dateToCompare = DateTime.Today;
YourTable.Where(t => SqlFunctions.DatePart("weekday", t.dateTimeField) - 1 == dateToCompare }); //Zero based in SQL

Linked


Related

Latest