简体   繁体   中英

Equality comparison fails between C# datetime and SQL datetime

I am trying to do an equality comparison between a C# datetime and a SQL datetime, which appears to fail due to the precision in which those values are stored.

So say I have a really simple SQL table, with these fields:

ID (PK, int, not null) - identity
Title (text, null)
UpdateTime (datetime, not null)

I create a class object via Entity framework, setting its UpdateTime to DateTime.Now like so:

DateTime now = DateTime.Now;
Title.UpdateTime = now;

When I insert my new object into the table, I see that all the values appear to be stored correctly. Now I want the ID that was created for my object.

This is where things get borked. I try pulling the ID back via LINQ:

Title.ID = context.DBTitles.Where(x=>x.UpdateTime == now).FirstOrDefault().ID;

This throws an exception because the query returns null, despite the fact that the 'now' I've inserted is supposedly the same as the 'now' that was inserted into my table.

So my question : How do I ensure that my C# datetime is equivalent to the datetime stored in SQL? What is the best way to get my ID back?

If you are using SQL server, use DateTime2 instead. It has the same precision as the .NET type.

If you're using Linq, won't the object you're inserting get the ID assigned to it upon commit? You won't need to 'recall' 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