Reputation: 1385
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?
Upvotes: 3
Views: 997
Reputation: 4328
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.
Upvotes: 3
Reputation: 46977
If you are using SQL server, use DateTime2
instead. It has the same precision as the .NET type.
Upvotes: 6