[SQL]MilliSecond毫秒精準度需利用SqlDateTime儲存
舉例來說:下列的方式絕對無法儲存到milli second精準度到SQLServer的,你下中斷點看到UpDate_Date欄位的milli second跟實際儲存到SQLServer的milli second絕對會差個0.00X秒:
private void UpdateExeSetup(string yOrN, string ip)
{
using (MyEntities db = new MyEntities())
{
var exeSetup = db.MyTable.Where(a => a.CODE_KIND == "myKind" & a.CODE_ID == "myId").FirstOrDefault();
exeSetup.Col1 = yOrN;
exeSetup.Col2 = ip;
exeSetup.Update_Date = DateTime.Now;
db.SaveChanges();
}
}
需改用下列SqlDateTime寫法才不會有毫秒誤差喔:
private void UpdateExeSetup(string yOrN, string ip)
{
using (MyEntities db = new MyEntities())
{
var exeSetup = db.MyTable.Where(a => a.CODE_KIND == "myKind" & a.CODE_ID == "myId").FirstOrDefault();
exeSetup.Col1 = yOrN;
exeSetup.Col2 = ip;
//要使用new SqlDateTime才會精準到 millisecond喔
exeSetup.Update_Date = new SqlDateTime(DateTime.Now).Value;
db.SaveChanges();
}
}
參考資料:
Round .NET DateTime milliseconds, so it can fit SQL Server milliseconds