如何仅从实体框架中的日期时间字段搜索日期? [英] How do I search for date only from a datetime field in entity framwork?

查看:66
本文介绍了如何仅从实体框架中的日期时间字段搜索日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我从包含日期和时间的表格查询,即2016-08-16 09:26:30.413



,当我使用c#查询使用表格时,如下所示,我得不到任何结果..例如;



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;

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.





我如何使用Entitty Framwork搜索日期?



我尝试了什么:



我刚刚在线搜索我如何实现这一目标但仍然没有运气!



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!

推荐答案

尝试



try

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


有一个数字您可以用来查找记录的选项,而不用将整个表格加载到内存中。



例如,这个可以工作并将利用日期列上的索引:

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:
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:

DateTime date = new DateTime(2016, 8, 6);
var entity = context.Table.FirstOrDefault(x => DbFunctions.TruncateTime(x.Datefield) == date);


这篇关于如何仅从实体框架中的日期时间字段搜索日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆