如何使用实体框架向数据库服务器询问当前日期时间?

发布于 2024-08-28 05:15:31 字数 362 浏览 10 评论 0原文

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

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

不管怎样,如果你能帮助我从数据库服务器检索当前的日期时间,那将会有很大的帮助。

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.

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?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

暮年 2024-09-04 05:15:31

是否有原因导致您无法将其推送到数据库?如果您在实体查询中包含 DateTime.Now,它会将其下推 (getdate) 到数据库。

示例 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]

可能是更好的方法吗?

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.

Example linq to entities

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

SQL Generated ..

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

Might be a better way to do it ?

寄人书 2024-09-04 05:15:31

这是 @Nix 对 EF4 响应的更新:

var dateQuery = dbContext.Database.SqlQuery<DateTime>("SELECT getdate()");
DateTime serverDate = dateQuery.AsEnumerable().First();

This is an update of @Nix response to EF4:

var dateQuery = dbContext.Database.SqlQuery<DateTime>("SELECT getdate()");
DateTime serverDate = dateQuery.AsEnumerable().First();
漫雪独思 2024-09-04 05:15:31

.net core 2.0 的更新

var dual =  databaseContext
            .Set<Dual>()
            .FromSql("SELECT -1 AS Id, GETDATE() AS DateTime")
            .First();

假实体

public class Dual
{
    public int Id { get; set; }
    public DateTime DateTime { get; set; }
}

An update for .net core 2.0

var dual =  databaseContext
            .Set<Dual>()
            .FromSql("SELECT -1 AS Id, GETDATE() AS DateTime")
            .First();

The fake entity

public class Dual
{
    public int Id { get; set; }
    public DateTime DateTime { get; set; }
}
此刻的回忆 2024-09-04 05:15:31

EF 3

var dual = await db
            .Set<Dual>()
            .FromSqlRaw(@"
                SELECT 
                    CURRENT_TRANSACTION_ID() as Id, 
                    SYSDATETIMEOFFSET() AS DateTime
            ")
            .FirstAsync();
DateTimeOffset serverTime = dual.DateTime;

public class Dual
{
    public long Id { get; set; }
    public DateTimeOffset DateTime { get; set; }
}

modelBuilder.Entity<Dual>(entity =>
{
    entity.HasNoKey();
    entity.ToView(nameof(Dual));
});

EF 3

var dual = await db
            .Set<Dual>()
            .FromSqlRaw(@"
                SELECT 
                    CURRENT_TRANSACTION_ID() as Id, 
                    SYSDATETIMEOFFSET() AS DateTime
            ")
            .FirstAsync();
DateTimeOffset serverTime = dual.DateTime;

public class Dual
{
    public long Id { get; set; }
    public DateTimeOffset DateTime { get; set; }
}

modelBuilder.Entity<Dual>(entity =>
{
    entity.HasNoKey();
    entity.ToView(nameof(Dual));
});
许一世地老天荒 2024-09-04 05:15:31

在VS 2008中,如果添加函数模板来返回标量,则不会添加代码以使其易于使用。您需要直接访问函数模板——我使用分部类来构建所需的方法以方便使用。他们在 VS2010 中修复了这个问题。

    public DateTime GetDateTime()
    {
        var returnValue = new DateTime();
        using (var connection = new EntityConnection(Connection.ConnectionString))
        {
            connection.Open();
            using (var command = connection.CreateCommand())
            {
                command.CommandText = "myStoredProc";
                command.CommandType = CommandType.StoredProcedure;
                try
                {
                    returnValue = Convert.ToDateTime(command.ExecuteScalar());
                }
                finally
                {
                    connection.Close();
                }
            }
        }
        return returnValue;
    }

更多信息:
具有非实体的实体模型中的函数导入返回类型

In VS 2008, if you add a function template to return a scalar, it does not add the code to make it easy to use. You need to access the function template directly -- I use the partial class to build the needed methods for ease of use. They fixed this in VS2010.

    public DateTime GetDateTime()
    {
        var returnValue = new DateTime();
        using (var connection = new EntityConnection(Connection.ConnectionString))
        {
            connection.Open();
            using (var command = connection.CreateCommand())
            {
                command.CommandText = "myStoredProc";
                command.CommandType = CommandType.StoredProcedure;
                try
                {
                    returnValue = Convert.ToDateTime(command.ExecuteScalar());
                }
                finally
                {
                    connection.Close();
                }
            }
        }
        return returnValue;
    }

More information:
Function Imports in Entity Model with a non-Entity Return Type

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文