EntityFramework獲取資料庫的時間
阿新 • • 發佈:2019-01-05
由於本地時間和資料庫時間可能不一致, 所以我們常常抓取資料庫的時間作為我們資料的時間,那在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(),程式碼如下。
這樣就確保了資料庫時間的獲取,為了方便使用,我們可以將這段程式碼封裝到XXEntities : DbContext的部分類中。比如var now = this.Database.SqlQuery<DateTime?>("SELECT GetDate()").First(); if (now == null) { now = new DateTime(1900, 1, 1, 0, 0, 0); } return now.Value;
在需要的地方,只要如下呼叫即可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()
轉載請註明出處。