Entity Framework 7: get database time

旧巷老猫 提交于 2019-12-08 09:45:18

问题


What is the best method to get the database server time in EF7? I discovered so far that is currently no support for query with output parameters.


回答1:


If you only want to use Entity Framework, you can do it like that:

  • Having this context:

    // My Dbcontext
    public class EF7Context : DbContext { }
    
  • And the utility function:

    public static DateTime GetDbDateTime()
    {
        using (var context = new EF7Context())
        {
            using (var connection = context.Database.GetDbConnection())
            {
                if (connection.State == ConnectionState.Closed)
                {
                    connection.Open();
                }
    
                var command = connection.CreateCommand();
                command.CommandText = "select SYSUTCDATETIME()";
                return (DateTime)command.ExecuteScalar();
            }
        }
    }
    



回答2:


Done using ADO.NET approach:

public DateTime GetServerUtcNow()
{
    using (var connection = new SqlConnection(_settings.ConnectionString))
    {
        connection.Open();
        var command = connection.CreateCommand();
        command.CommandText = "select SYSUTCDATETIME()";
        return (DateTime)command.ExecuteScalar();
    }
}


来源:https://stackoverflow.com/questions/35077000/entity-framework-7-get-database-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!