Getting DB Server DateTime in application
I am using Entity framework and have 1 field in database AddedDate that is DateTime and not null, so I need to pass DateTime value.
But the problem is I have to pass DB Server datetime. How can I manage in this sceario or h开发者_C百科ow can I get DB Server datatime to pass this.
I need to some unique solution, because I am this on many forms.
Edit: I need DB server Datetime upon insertion/updation in my application so that I can pass to entity framework object.
Thanks
Since you are using entity framework, you can do something like this:
var dateQuery = yourDbContext.CreateQuery<DateTime>("CurrentDateTime() ");
DateTime dateFromSql = dateQuery .AsEnumerable().First();
In general, if you use the entity framework and you use DateTime in a field, it will automatically do the back/forth conversion for you, just the same way it does so for integers, doubles etc.
Unless you mean something special, i.e., a char[40] field that must be filled with a DateTime value of a particular format.
You can get database server date and time by running SELECT GETDATE()) script.
Consider you have a table with 4 colums - the first 3 being strings and the last datetime, You can solve your issue by issueing INSERT SQL like this:
INSERT INTO myTable VALUES ('x', 'y', 'z', SELECT GETDATE())
Can't you use a stored procedure so you can get DB server Datetime very easily.
Just use getdate() in your query. For example:
INSERT INTO your_table (AddedDate, ...other columns) VALUES (getdate(), ...other values)
This basically asks the server to insert its own current date into the field; there's no need for you to retrieve it locally.
精彩评论