简体   繁体   English

C#datetime和SQL datetime之间的平等比较失败

[英]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. 我试图在C#datetime和SQL datetime之间进行相等比较,由于存储这些值的精度,它似乎失败了。

So say I have a really simple SQL table, with these fields: 所以说我有一个非常简单的SQL表,包含以下字段:

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: 我通过Entity框架创建一个类对象,将其UpdateTime设置为DateTime.Now,如下所示:

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. 现在我想要为我的对象创建的ID。

This is where things get borked. 这是事情变得困难的地方。 I try pulling the ID back via LINQ: 我尝试通过LINQ拉回ID:

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. 这会引发异常,因为查询返回null,尽管我插入的'now'应该与插入到我的表中的'now'相同。

So my question : How do I ensure that my C# datetime is equivalent to the datetime stored in SQL? 所以我的问题是:我如何确保我的C#datetime等同于SQL中存储的日期时间? What is the best way to get my ID back? 获取我的身份证的最佳方法是什么?

If you are using SQL server, use DateTime2 instead. 如果您使用的是SQL Server,请改用DateTime2 It has the same precision as the .NET type. 它具有与.NET类型相同的精度。

If you're using Linq, won't the object you're inserting get the ID assigned to it upon commit? 如果您正在使用Linq,那么您插入的对象是否会在提交时获得分配给它的ID? You won't need to 'recall' it. 你不需要“回忆”它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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