简体   繁体   中英

c# SQL Server : DATETIME datatype

I am writing a unit test which stores an object with a DateTime parameter into a DATETIME2 SQL Server database column. I then create a temporary DateTime object called new_date_time and set that value to DateTime.Now .

The new_date_time value is then used to update the previous value and the SQL query to do this completes successfully.

When re-reading the object back from the database I receive the correct datetime values for days/hours/minutes but the .Ticks value is different from the new_date_time variables .Ticks property. The value returned from the read call returns the last 4 digits of the .Ticks property as zeros.

Why is this rounding occurring making my Assert.AreEqual fail?? :)

Thanks

I guess you are using Parameters.AddWithValue when writing the date to Sql Server. From MSDN the inferred type of a CLR DateTime is SqlDbType.DateTime and not SqlDbType.DateTime2 so the precision is being lost when writing your date to the database.

Explicitly setting the type to datetime2 will solve the issue. For example:

command.Parameters.AddWithValue("@now", DateTime.Now).SqlDbType = 
                                                       SqlDbType.DateTime2;

Edit

@marc_s makes a good point with his comment:

You should read (and embrace!) Can we stop using AddWithValue() already?

To avoid these kind of issues from biting you, you could get into the habit of using the Add method on the parameters collection which takes the SqlDbType in some overloads and then set the Value property on that rather than using the AddWithValue method:

command.Parameters.Add("@now", SqlDbType.DateTime2).Value = DateTime.Now;

Maybe your database field is not storing your entire DateTime.Now value, because it's not precise enough. Why don't you simply compare your dates after you've formatted them as you like?

eg: (untested):

var databaseDate = d1.ToString("MM/dd/yyyy HH:mm:ss.fff");

var tempDate = d2.ToString("MM/dd/yyyy HH:mm:ss.fff");

Assert.AreEqual(databaseDate, tempDate);

I tested: using Linq To Entities My DateTime.Now is correctly saved to my datetime2(7) and equality test return True .

Are you sure you're passing your correct datetime value to the database? without truncating it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM