DateTime Insert via LINQ - c#

I have a column in my table which has a DataType of 'timestamp'. Now I am inserting a row through LINQ2SQL. Now what should I write here:
Entity_Product_Point ev = new Entity_Product_Point();
ev.DateCreated = ???
Thanks!

Are you SURE you wanted timestamp? It has nothing to do with dates... If you'd like to store "DateCreated", I think you probably want to use either a DateTime or just Date datatype in MSSQL. If that's what you really intended, then you can pass in DateTime.Now for a value.

Well the corresponding type would be byte[], but this type is used internally by SQL Server for row versioning—and by ORMs for optimistic locking. You should never (can't) write a value out for a timestamp column manually.
For a more complete listing of which type correspond to what, check out this question

Related

Postgres and c# - DateTime with timezone confusion

Hopefully not a repost of another... a rather simple question, but I think I'm fundamentally confused about how dates/times with timezones are handled between Postgres and c#.
Simple situation, at one point in the program I call DateTime.Now and save to a variable 'now'. This is inserted into a Postgres DB.
cmd.Parameters.AddWithValue("createdat", now);
Great. The column that this is inserted into is of type "timestamp with time zone". When I view the result from something like DataGrip or DBeaver the raw data is exactly what I want (I think).
2021-03-09 15:07:51
Later on I query this table in a rather simple way.
SELECT createdat FROM mytable WHERE mycondition;
I cast it as a c# DateTime type and populate a class with it.
while (reader.Read())
{
myClass.createdAt = (DateTime) reader["createdat"];
}
However, the value is populated as the following:
3/9/2021 10:07:51 AM
Something is not working here. First, if the column in the DB is of timestamp with time zone, where is the time zone information? Second, if the time zone is working, since it is being both populated and queried from the same computer, why is there a discrepancy? Third, and the pressing issue, how do I solve this? Must I explicitly define the time zone? I'm confused as to why it is returning different data... Hopefully, someone can help me out.
I think Dbeaver is changing the time zone, but the data inserted is the same you get on c#. Try to check directly on the server using commandline because maybe dbeaver is changing it to diplay on your pc

Datetime format is 'mm-dd-yyyy' when getting while using SqlDataAdapter but if I run the same query in ms sql then its 'yyyy-mm-dd'

I know the question is a bit confusing. Please let me elaborate.
Suppose
I have a table student master which has a column DOB
I have inserted a record and in DOB I have inserted '1991-01-01'
running select statement from sql server is returning date in the same format as it is inserted '1991-01-01' but when I am running the same query from C# using SqlDataAdapter then its returning date as '01-01-1991'
Can anyone explain why it is happening and is there any way to fetch the date in same format as it is inserted.
Query
Is it possible to get the DateTime using SqlDataAdapter as it was inserted?
P.S: column data type is Datetime
let's separate the wheat from the chaff :)
if for your needs meaningful is data type (datetime in this case), then formatting does not matter at all. All layers which will exchange or process the data will use data type information for that.
But
if the meaningful part is formatting, i.e. string representation of the data, then you need to consider the appropriate settings of UI tools you use to display your data. SSMS, for example, uses regional settings for that. If you need to visualize data in the identical manner, so you need the identical strings, you should take care of formatting by your self or in another words, you need to convert your datetime data to string in the same way in all places where you need it.
In T-SQL, for example, you could use CAST and CONVERT functions for formatting your data in a format you need.
If you can't match up the "Cultures" between the SQL Server and the machine you're building the application on (and, in fact, you cannot rely on that really if you're application is going to be deployed to other machines!), then the cheap and quick way round it is to run your date returns through a parse function such as this:
private string FncFormatDate(string date)
{
DateTime formattedDate;
if (DateTime.TryParse(date, out formattedDate))
{
return formattedDate.ToString("yyyy-MM-dd");
}
else
{
return "Invalid date";
}
}
I hope this answers your question.

How to retrieve Timestamp value from SQL Server using DataReader

How to retrieve Timestamp value(eg:0x000000048E18B9D8 ) from SQL Server using DataReader? I'm getting an IndexOutOfRangeException when doing like this
DateTime date = reader.GetDateTime(reader.GetOrdinal("Timestamp"));
Can anyone help on this?
Also I want to know how to pass timestamp parameter to stored procedure using .Net code
IndexOutOfRangeException thrown on reader.Getordinal() suggests that a column called Timestamp doesn't exist. Check your column names again, and replace with the actual value. By default, it will be called timestamp, but only if you haven't specified a column name.
You could also try string ts = reader["timestamp"].toString(), and make sure it returns something.
According to MSDN, a TIMESTAMP data type is "8 bytes...[and]... just an incrementing number and does not preserve a date or a time. To record a date or time, use a datetime data type."
Therefore, reader.GetInt64() is probably close, if you really need this value, but byte[] myTimestamp = reader["timestamp"] is probably better.
As far as passing it back to your stored procedure, you can create a new parameter with SqlDbType.Timestamp. The value will be a byte array, or, if you have it stored as a string, you could try something like:
cmd.Parameters.Add("#TimeStampParam", SqlDbType.Timestamp).Value = System.Text.Encoding.ASCII.GetBytes(myTimestampStr);`
(NB: I haven't tested this, but it should be close enough).
Note that TIMESTAMP is deprecated, and ROWVERSION is not the preferred syntax.

c# SQL Server : DATETIME datatype

I am writing a unit test which stores an object with a DateTime parameter into a DATETIME2 SQL Server database column. I then create a temporary DateTime object called new_date_time and set that value to DateTime.Now.
The new_date_time value is then used to update the previous value and the SQL query to do this completes successfully.
When re-reading the object back from the database I receive the correct datetime values for days/hours/minutes but the .Ticks value is different from the new_date_time variables .Ticks property. The value returned from the read call returns the last 4 digits of the .Ticks property as zeros.
Why is this rounding occurring making my Assert.AreEqual fail?? :)
Thanks
I guess you are using Parameters.AddWithValue when writing the date to Sql Server. From MSDN the inferred type of a CLR DateTime is SqlDbType.DateTime and not SqlDbType.DateTime2 so the precision is being lost when writing your date to the database.
Explicitly setting the type to datetime2 will solve the issue. For example:
command.Parameters.AddWithValue("#now", DateTime.Now).SqlDbType =
SqlDbType.DateTime2;
Edit
#marc_s makes a good point with his comment:
You should read (and embrace!) Can we stop using AddWithValue() already?
To avoid these kind of issues from biting you, you could get into the habit of using the Add method on the parameters collection which takes the SqlDbType in some overloads and then set the Value property on that rather than using the AddWithValue method:
command.Parameters.Add("#now", SqlDbType.DateTime2).Value = DateTime.Now;
Maybe your database field is not storing your entire DateTime.Now value, because it's not precise enough. Why don't you simply compare your dates after you've formatted them as you like?
eg: (untested):
var databaseDate = d1.ToString("MM/dd/yyyy HH:mm:ss.fff");
var tempDate = d2.ToString("MM/dd/yyyy HH:mm:ss.fff");
Assert.AreEqual(databaseDate, tempDate);
I tested: using Linq To Entities My DateTime.Now is correctly saved to my datetime2(7) and equality test return True.
Are you sure you're passing your correct datetime value to the database? without truncating it?

Different format for timestamp when using c# datareader

I'm reading a timestamp from a mysql table using an OdbcDataReader. When I look at the data in the table it is in the format 2013-09-12 11:11:09. But the reader seems to read it in the format 12/09/2013 11:11:09.
I then try to insert this into another mysql table but receive the error:
Incorrect datetime value: '12/09/2013 11:11:09' for column 'timestamp'
at row 1
How can I sort out this difference in formatting? Should I be referencing some Unix timestamp value somehow?
The data shouldn't be in the table in any text format. It's just a date and time.
You'll see the format when you convert the data to a string - which you should do as rarely as possible. In particular, when you're inserting the data into a different table, you shouldn't use a formatted value at all - you should use a DateTime in parameterized SQL.
Basically, unless you really need a string representation of the data, you should keep it in the "native" representation (DateTime in this case). Every time you have a conversion to or from text, that's an opportunity for failure. Dates and times are hard enough with time zones etc, without extraneous conversions getting involved.
How are you looking at the data "in the table"? I'm not familiar with the MySQL implementation, but with Oracle and Sql Server datetime values are stored in an unreadable binary format, and translated to a readable timestamp by the query tool. MySQL is likely doing something similar.
try to insert this into another mysql table
If you care about format when you're inserting the data, you're doing something really bad. That's a strong indication you're using a technique that will be vulnerable to sql injection attacks, rather than parameterized queries. If you use parameterized queries, you assign a C# datetime type to the query parameter value directly, and the ADO.Net object handles any formatting you need. At that point, anything you can successfully DateTime.Parse() or DateTime.TryParse() becomes a valid input for your query.

Categories

Resources