My table structure in sql server is :
TableId int (Pk) identity
Data string
DateNTime DateTime
My method is::
public int insertData(string data){
Date= DateTime.Now;
Table table= new Table();
table.Data= data;
table.DateNTime=Date;
this.DataContext.Set<Table>().Add(table);
this.DataContext.SaveChanges();
return this.DataContext.Tables.Single(b => b.DateNTime == Date).TableId
}
The data insertion happens without any problems but in 9 out of 10 times while returning TableId I get the exception “sequence contains no elements”
Could it be that before the table row is saved the select command is fired and I get this error, if so what do I do?
Thanks
Arnab
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
DateTimein .NET you’ll see (for example in theTimeOfDayproperty):TimeOfDay of .NET
DateTimetype: 10:32:51.0312500So, the precision is 10E-7 seconds. A
datetimein SQL Server has only 10E-3 seconds precision and the .NETDateTimeis saved like this in the database:Column value of SQL Server
datetimetype: 10:32:51.030So, it is rounded to three digits. When you run the query the .NET
DateTimeis transmitted with high precision (as typedatetime2(7)in SQL Server) …… and the equality comparison fails because
2012-05-18 10:32:51.0312500!=2012-05-18 10:32:51.030If you want a higher precision use a
datetime2(7)as type in SQL Server that matches the .NETDateTimetype. Or avoid such queries for equality and instead query for an interval of +/- 1 second or something around yourDateTimevalue, like so:(Not a good solution of course if you save faster than every 2nd second,
Singlemight fail with “Sequence contains more than one element” exception.)