How do I perform Date Comparison in EF query?

后端 未结 11 1282
悲哀的现实
悲哀的现实 2020-11-30 07:33

Please help. I am trying to figure out how to use DATE or DATETIME for comparison in a linq query.

Example: If I wanted all Employee names for those who started befo

相关标签:
11条回答
  • 2020-11-30 07:56

    You can check the condition like this

    var nextDay = DateTime.Today.AddDays(1);
    
    var query = from e in db.MyTable
                where e.AsOfDate >= DateTime.Today && e.AsOfDate < nextDay 
                select e;
    

    here you'll get the records on AsOfDate date as we checking between today(00:00:00) and tommorow(00:00:00) we'll get today's date record only what ever may be the time...

    0 讨论(0)
  • 2020-11-30 07:56

    I am using a LinqDataSource and I had problems getting my query with a Date Comparison in it to execute without errors. The answer is to use the WhereAddParameters function and add the test value as a strongly typed parameter.

    See the example below where I am matching a groupid and checking to see if the StopDate in my record is greater that or equal to a Date/Time stamp of now.

    I am using this code fragment currently and it works like a charm.

    LinqCampaigns.WhereParameters.Add("StopDate", System.Data.DbType.Date, DateTime.Now.ToString())
    LinqCampaigns.Where = "GroupId = " & myGrp & " &&  " & "StopDate >= @StopDate"
    

    Works like a charm....

    0 讨论(0)
  • 2020-11-30 07:57

    Use the class DbFunctions for trimming the time portion.

    using System.Data.Entity;
    
    var bla = (from log in context.Contacts
               where DbFunctions.TruncateTime(log.ModifiedDate) 
                                  ==  DbFunctions.TruncateTime(today.Date)
               select log).FirstOrDefault();
    

    Source: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/84d4e18b-7545-419b-9826-53ff1a0e2a62/

    0 讨论(0)
  • 2020-11-30 07:57

    use a local variable to store the Date value and then use that variable in the query:

    DateTime today = DateTime.Now.Date; from scheme in context.schemes where scheme.EndDate > today select scheme

    0 讨论(0)
  • 2020-11-30 08:02

    ensure that you check null value like this :

     '(from mm in _db.Calls 
       where mm.Professionnal.ID.Equals(proid)
       && mm.ComposedDate.HasValue &&
       (mm.ComposedDate.Value >= datemin) && (mm.ComposedDate.Value <= date)
       select mm).ToArray();'
    
    0 讨论(0)
提交回复
热议问题