如何使用实体框架向数据库服务器查询当前日期时间? [英] How to ask the database server for current datetime using entity framework?

查看:148
本文介绍了如何使用实体框架向数据库服务器查询当前日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有ModifiedDateTime属性的实体,我想用数据库中的当前日期时间来更新该实体,而不是执行该应用程序的应用程序"服务器.

I have an entity with a ModifiedDateTime property which I want to be updated with the current datetime from the database instead of the "application" server executing the application.

每次我想在SQL Server 2008的数据库中更新或添加一个人时,我都想填写ModifiedDateTime字段.当我使用数据集并为我的ModifiedDateTime字段定义为GetDate()时,并不能像使用数据适配器命令一样更改更新查询.我创建了存储函数以向我返回GetDate()方法的值,但是在导入过程时遇到了问题,该过程返回的值是int,字符串或根本没有值,例如对于我来说,已经只是实体值(例如Person).这是为什么?

Every time I want to update or add a person to my datebase on SQL Server 2008 I want to fill ModifiedDateTime filed. It's not like I can change update query as with data adapter command when I work with dataset and to define for my ModifiedDateTime filed to be GetDate(). I created stored function to return me a value of GetDate() method, but I have a problem to import procedure which returns values as int, string or no value at all, already just entity values as Person for example in my case. Why is that?

无论如何,如果您能帮助我从数据库服务器检索当前的DateTime,那将有很大的帮助.

Anyway, it would be of great help if you can help me to retrieve the current DateTime from the database server.

推荐答案

您是否有理由不能将其推送到数据库?如果您在实体查询中包含DateTime.Now,它将把它下推(获取日期)到数据库中.

Is there a reason you just can't push it down to your database? If you include DateTime.Now in your entity query, it will push it down (getdate) to the database.

实体的linq示例

 var dQuery = dbContext.CreateQuery<DateTime>("CurrentDateTime() ");
 DateTime dbDate = dQuery.AsEnumerable().First();

SQL生成的..

SELECT GetDate() AS [C1] FROM  ( SELECT cast(1 as bit) AS X ) AS [SingleRowTable1]

可能是更好的方法吗?

Might be a better way to do it ?

这篇关于如何使用实体框架向数据库服务器查询当前日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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