DateTime insertion and then selection: sequence contains no elements

前端 未结 1 1052
离开以前
离开以前 2021-01-25 09:46

My table structure in sql server is :

TableId int (Pk) identity

Data string

DateNTime DateTime

My method is::

public in         


        
1条回答
  •  庸人自扰
    2021-01-25 10:25

    SaveChanges() is a synchronous "blocking" operation, it doesn't return before the transaction that saves the date is committed. So, when you call the query the date is definitely saved in the database.

    I think, it is a precision/rounding problem. If you look at the precision of a DateTime in .NET you'll see (for example in the TimeOfDay property):

    TimeOfDay of .NET DateTime type: 10:32:51.0312500

    So, the precision is 10E-7 seconds. A datetime in SQL Server has only 10E-3 seconds precision and the .NET DateTime is saved like this in the database:

    Column value of SQL Server datetime type: 10:32:51.030

    So, it is rounded to three digits. When you run the query the .NET DateTime is transmitted with high precision (as type datetime2(7) in SQL Server) ...

    WHERE [Extent1].[MyDateTimeColumn] = @p__linq__0',
        N'@p__linq__0 datetime2(7)', @p__linq__0='2012-05-18 10:32:51.0312500'
    

    ... and the equality comparison fails because

    2012-05-18 10:32:51.0312500 != 2012-05-18 10:32:51.030

    If you want a higher precision use a datetime2(7) as type in SQL Server that matches the .NET DateTime type. Or avoid such queries for equality and instead query for an interval of +/- 1 second or something around your DateTime value, like so:

    var date1 = Date.AddSeconds(-1);
    var date2 = Date.AddSeconds( 1);
    return this.DataContext.Tables
        .Single(b => b.DateNTime >= date1 && b.DateNTime <= date2)
        .TableId;
    

    (Not a good solution of course if you save faster than every 2nd second, Single might fail with "Sequence contains more than one element" exception.)

    0 讨论(0)
提交回复
热议问题