• EntityFramework获取数据库的时间


    由于本地时间和数据库时间可能不一致, 所以我们常常抓取数据库的时间作为我们数据的时间,那在EntityFramework中要如何抓取时间呢?网上常见的做法是利用SqlFunctions.GetDate(),但是该函数必须要放到模型中来执行才可以,代码如下

      var now = this.TUser.Select(t => SqlFunctions.GetDate()).FirstOrDefault();
                if (now == null)
                {
                    now = new DateTime(1900, 1, 1, 0, 0, 0);
                }
                return now.Value;

    其中TUser是数据库中的一个表,用其他表也是可以的。一般情况下是没有问题的。但是当用于查询的表,比如这里的TUser中没有任何数据时,返回的时间是空的。为何呢?因为该函数是依赖于select查询行数据,没有任何数据时,自然得不到结果。为此我们采用另外一种方法,直接SELECT GETDATE(),代码如下。

    var now = this.Database.SqlQuery<DateTime?>("SELECT GetDate()").First();
                if (now == null)
                {
                    now = new DateTime(1900, 1, 1, 0, 0, 0);
                }
                return now.Value;
    这样就确保了数据库时间的获取,为了方便使用,我们可以将这段代码封装到XXEntities : DbContext的部分类中。比如

    namespace XXModel
    {
        using System;
        using System.Data.Entity;
        using System.Data.Entity.Infrastructure;
        using System.Data.Entity.SqlServer;
        using System.Linq;
    
        public partial class XXEntities : DbContext
        {
            /// <summary>
            /// 自定义连接串
            /// </summary>
            /// <param name="Connstring"></param>
            public KingEntities(string Connstring)
                : base(Connstring)
            {
    
            }
    
            #region FetchDBDateTime Function              
            /// <summary>
            /// 获取数据库的当前时间
            /// </summary>
            /// <returns></returns>
            public DateTime FetchDBDateTime()
            {
                var now = this.Database.SqlQuery<DateTime?>("SELECT GetDate()").First();
                if (now == null)
                {
                    now = new DateTime(1900, 1, 1, 0, 0, 0);
                }
                return now.Value;
            }
            #endregion
        }
    }
    
    在需要的地方,只要如下调用即可

    dbContext.FetchDBDateTime() 

    转载请注明出处。


  • 相关阅读:
    由“Jasperrpeorts 4.1.2升级到5.1.2对flex项目的解析”到AS3 带命名空间的XML的操作
    c++里的类型转化
    A股市场暴跌背后的三大元凶?
    jQuery简单过滤选择器
    Handling of asynchronous events---reference
    NMAP
    JVM Run-Time Data Areas--reference
    Getting over the dangers of rm command in Linux---reference
    45 Useful Oracle Queries--ref
    手动修改user-agent
  • 原文地址:https://www.cnblogs.com/sparkleDai/p/7604919.html
Copyright © 2020-2023  润新知