Click here to Skip to main content
15,897,273 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,
I am querying from table that contains a date and time i.e "2016-08-16 09:26:30.413"

when i query using the table using c# like below i get no results .. for example;

C#
DateTime date = "2016-08-16"
DateTime date2 = "2016-08-16 09:26:30.413"
var getdate = context.Table.Where(x => x.Datefield == date).FirstOrDefault(); //This returns no results
var getdate = context.Table.Where(x => x.Datefield == date)2.FirstOrDefault(); // thsi returns the results.


How would i go about in searching for Date Only using Entitty Framwork?

What I have tried:

I have just been searching online on how i can go about in achieving this but still no luck!
Posted
Updated 15-Nov-17 6:51am

try

C#
string inputdate = "2016-08-16";
var val = context.Table.ToList().Where(k => k.DateField.ToString("yyyy-MM-dd") == inputdate).FirstOrDefault();


please refer Richard's solution for alternate and efficient way to achieve this
 
Share this answer
 
v3
Comments
1Future 15-Nov-17 4:08am    
Hi , Thank you for your time.. i'm now getting the folllowing error LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.
Karthik_Mahalingam 15-Nov-17 4:11am    
DateField is string or DateTime Type ?
1Future 15-Nov-17 4:12am    
Its DateTime Type
Karthik_Mahalingam 15-Nov-17 4:17am    
 string inputdate = "2016-08-16";
context.Table.ToList().Where(k => k.DateField.ToString("yyyy-MM-dd") == inputdate).FirstOrDefault();
1Future 15-Nov-17 4:20am    
Hi , am i missing out anything different in this from the first solution you provided? I'm still getting the same error unfortunately
There are a number of options you can use to find the records without loading the entire table into memory.

For example, this one works and will take advantage of an index on the date column:
C#
DateTime date = new DateTime(2016, 8, 6);
DateTime nextDay = date.AddDays(1);

var entity = context.Table.FirstOrDefault(x => x.Datefield >= date && x.Datefield < nextDay);

This one won't be able to use an index, but will still work:
C#
DateTime date = new DateTime(2016, 8, 6);
var entity = context.Table.FirstOrDefault(x => DbFunctions.TruncateTime(x.Datefield) == date);
 
Share this answer
 
Comments
Karthik_Mahalingam 15-Nov-17 22:33pm    
5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900