I'm struggling as why my DateTime is saved incorrectly into my database.
I pass it the value 20/12/2015 (as a string) alongside the format (dd/MM/yyyy) and parse it into a DateTime but it always saves into my SQL Server database as 06/12/2015
public ActionResult SaveSettings(ProjectPlan projectPlan)
{
projectPlan.StartDate = DateTime.ParseExact(projectPlan.ShortDateTime, projectPlan.DateFormat, null); //ShortDateTime is 20/12/2015, DateFormat is dd/MM/yyyy
var plan = this._dc.ProjectPlans.Single(a => a.Id == projectPlan.Id);
plan = projectPlan;
this._dc.SaveChanges();
}
Erm, didn't you mean updating the StartDate property of your entity and then saving it back into the database:
public ActionResult SaveSettings(ProjectPlan projectPlan)
{
var plan = this._dc.ProjectPlans.Single(a => a.Id == projectPlan.Id);
plan.StartDate = DateTime.ParseExact(projectPlan.ShortDateTime, projectPlan.DateFormat, null);
this._dc.SaveChanges();
}
On this line you are basically killing every context EF knows about:
plan = projectPlan;
So if you looked at the actual SQL query generated against your SQL database you would have noticed that exactly 0 rows were updated.
The textual representation is not stored in the server, neither is it in .NET when you have a DateTime object. It is just a large number counting the number of "ticks" from a set time.
You will need to format the date when you select the date out back in to a string, the inserting side can't control it (unless the inserting side also stores the formatting string or you don't store it as a date and instead store it as a string)
Related
i have a query where i am passing value in given below format it is working in oracle pl/sql
Select ASE_ID
from ASE_DTLS a
where TO_CHAR(CRT_ON,'YYYY-MM-DD')
between '2020-09-01' and '2020-09-23'
Above query giving output. but when i am trying to pass it through c# query in given below format it is not returning value.
Select ASE_ID
from ASE_DTLS a
where TO_CHAR(CRT_ON,'YYYY-MM-DD')
between :CRT_ON and :CRT_ON";
reciving value from post method in fieldval[0] in '01-09-2020 00:00:00' & '23-09-2020 00:00:00' format.
command.Parameters.Add(":CRT_ON", fieldval[0].From.ToString("yyyy-MM-dd"));
command.Parameters.Add(":CRT_ON", fieldval[0].To.ToString("yyyy-MM-dd"));
while reading it through ExecuteReader getting 0 record.
From & To are as defined in c#
public DateTime From { get; set; }
public DateTime To { get; set; }
and CRT_ON in oracle as date.
Dates both in .NET and Oracle have no format, they are binary values. The query should use parameters with date-related types, not convert the dates to strings, only to convert them back to dates.
The code has other problems too - the same parameter is added twice, with a different value. The query itself is using that single parameter in the BETWEEN clause, effectively turning it into an equality check.
The query should be :
Select ASE_ID
from ASE_DTLS a
where CRT_ON between :CRT_FROM and :CRT_TO
The parameters' type should be DateTime :
var fld=fieldval[0];
command.Parameters.Add(":CRT_FROM", OracleDbType.Date).Value = fld.From.Date;
command.Parameters.Add(":CRT_TO", OracleDbType.Date).Value = fld.To.Date;
DateTime.Date returns only the date part of a DateTime value.
This will work as-is if CRT_ON is a date. If it's a timestamp, the query would return rows only up to :CRT_TO at 00:00. To return dates on that day, the query would have to change to
Select ASE_ID
from ASE_DTLS a
where CRT_ON >= :CRT_FROM and CRT_ON < :CRT_TO
And :CRT_TO should be incremented by one day:
var toParam=command.Parameters.Add(":CRT_TO", SqlDbType.DateTime);
toParam.Value = fld.To.Date.AddDays(1);
You should use date as date. Do not convert it to char.
Select ASE_ID from ASE_DTLS a where trunc(CRT_ON) between to_date('2020-09-01','YYYY-MM-DD') and to_date('2020-09-23','YYYY-MM-DD')
I am using Npgsql 3.0.3.0 and PetaPoco latest version.
When I run this command:
var dateCreated = DateTime.Now; // just an example
var sql = new Sql("WHERE date_created = #0", dateCreated.ToString("yyyy-MM-dd HH:00:00"));
var category = db.SingleOrDefault<Category>(sql);
I get the following error:
Npgsql.NpgsqlException 42883: operator does not exist: timestamp
without time zone = text
I understand the error message is saying I'm trying to compare a timestamp (date) with a text, however for me it's perfectly valid to compare them as I am expecting the following SQL statement to be built:
SELECT * FROM category WHERE date_created = '2017-02-03 15:00:00'
I don't really want to typecast my database column to text for performance reasons.
You need to cast value to timestsamp:
var sql = new Sql("WHERE date_created = #0::timestamp", dateCreated.ToString("yyyy-MM-dd HH:00:00"));
You need to explicit typecast text to timestamp.
Try using :
TO_TIMESTAMP(date_string,'YYYY-MM-DD')
As #roman-tkachuk answered, you can tell PostgreSQL to cast your string into a timestamp.
Or better yet, you can simply send a timestamp to PostgreSQL directly, rather than sending a string representation of a timestamp and having it cast. To do that, simply send dateCreated directly, without the ToString().
i have to compare a choosen Date from a Calendar (startdat & enddat) with a Date in my SQL 2008 R2 DB. I have to write it with LINQ, but in the view i have, the DateTime is converted to a String (Varchar) so i have to convert it in my LINQ Query back to DateTime. My basic Query looks like this now:
var reportlist = (from r in context.Monthly_Report
where r.CreateDate >= startdat && r.CreateDate <= enddat
select r.Ticketnumber).ToList();
So the CreateDate i get is a String and for comparing i've to convert it. I've tried it with Convert.ToDateTime() but there's is the Problem with L2E.
So how can i convert it like in a SQL Script or that SQL knows what i means?
Thanks for every help i get. (btw i'm not allowed to change the view)
You can only use a reduced set of functions in Linq to Entities. This functions will be transalated to DB functions.
You can use:
canonical functions: they're availabel for all the providers (DB tastes)
entity functions: exposes canonical functions in the EDM
db functions: exposes canonical functions in the EDM
sql functions: exposes SQL Server specific functions
None of these groups includes a function that can convert from string to datetime, so there is no way to do it directly.
You must look for alternatives:
Create a DB view which exposes the "stringified" datetime as a datetimecolumn and query it
Create a stored proc and use it
Convert the datetime to string and compare it, if at all possible (this depends on how the "stringified" datetime looks like)
You can use the previous solution using substrings (which will map to DB functions). This will work for all cases: reorder the y, m, d, of the "stringified" dt date, so that it looks like "yyyymmdd". Then convert your startdat and enddat to the same format, and compare it in string (alphabetic) order.
Fundamentally, you need your view to return a datetime.
However, there are a couple of ways to do this.
1) You could pull your data out as a string into a list object. Then you wouldnt be using L2E.
var temp = (from r in context.Monthly_Report
select new { r.Ticketnumber, r.CreateDate} ).ToList();
var reportList = temp.Where(r =>
Convert.ToDateTime(r.CreateDate) >= startdat &&
Convert.ToDateTime(r.CreateDate) <= enddat)
2) You could convert your datetime to a string value and compare it.
var reportlist = (from r in context.Monthly_Report
where r.CreateDate.CompareTo(startdatasstring) >= 0 &&
r.CreateDate.CompareTo(enddatasstring) <= 0
select r.Ticketnumber).ToList();
I'm wanting to call this stored procedure with input parameters:
proc [dbo].[Invoice_GetHomePageInvoices] (
#FinancialYearStartDate datetime = null
, #FinancialYearEndDate datetime = null
Trouble with this is the way I usually call a stored proc from my code is:
return _db.Database.SqlQuery<HomePageInvoice>(string.Format("EXEC Invoice_GetHomePageInvoices #FinancialYearStartDate = '{0}', #FinancialYearEndDate = '{1}'", financialYear.StartDate.ToString(), financialYear.EndDate.ToString()));
So this isn't going to work because I've basically converted my datetimes to strings.
How the heck am I supposed to do this?
You should use sql parameters, basically like this:
var startDate = new SqlParameter("FinancialYearStartDate", dateTimeValueHere);
var endDate = new SqlParameter("FinancialYearEndDate", dateTimeValueHere);
return _db.Database.SqlQuery<HomePageInvoice>("Invoice_GetHomePageInvoices", startDate, endDate);
More info: How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5
convert the date to a string with specific format.
use SQL code to convert it back to an sql datetime object.
When using sql server (microsoft):
http://msdn.microsoft.com/en-us/library/ms187928.aspx
"convert(datetime, '{0}', 103)", financialYear.EndDate.ToString("MM/dd/yyyy")
edit: Ropstah's method is actually better, this is just the way I used to do it :P
I am developing mobile application in C#. I am using the SQLite database to store the data. In the SQLite database I am storing the information related to the customer. In that I am storing the date with mm/dd/yy 12:54:30 PM format. Now I want to retrive the customer data based on start date & end date. I am using the following code
ShowRegistrationKeyDetails ShowRegKeyDetailsObj = new ShowRegistrationKeyDetails();
// set properties
ShowRegKeyDetailsObj.FromDate = FromdateTimePicker.Value.ToString();
ShowRegKeyDetailsObj.ToDate = TodateTimePicker.Value.ToString();
When I fire the SQL Queries based on these values I am not getting the proper result. I need to convert the above values of FromdateTimePicker.Text & TodateTimePicker.Text into the mm/dd/yy 12:54:30 PM format.
I am using the following code
public SQLiteDataReader getClient_And_RegistrationKeys(int Customer_ID, String FromDt, String ToDt)
{
SQLiteDataReader SQLLiteDrObj = null;
DataManager myDatabase = new DataManager("CompNet.db");
myDatabase.Init(false);
string[] Parameter = new string[] { "#Val_Customer_ID", "#Val_FromDt", "#Val_ToDt" };
Object[] Objval = new Object[] { Customer_ID, FromDt, ToDt };
string sqlCommandText = "Select Activation_Date, Standard_ID, Client_Key, Registration_Key from Activation_Details where Customer_ID=#Val_Customer_ID And Activation_Date between #Val_FromDt And #Val_ToDt";
SQLLiteDrObj = myDatabase.ExecuteReader(sqlCommandText, Parameter, Objval);
return SQLLiteDrObj;
}
I have tried this code. Now I am getting the date in the format in which I want but I am not getting the required rows as output. There is no row in the output. Where I am going wrong ? Can you please provide me any code?
Don't use Text to start with - use DateTimePicker.Value to get the value as a DateTime.
Ideally, then don't convert it into text when using SQLite either - use a parameterized query instead of formatting it at all. See this article as one example of using parameterized queries from C# with SQLite.
As a general rule, try to avoid going through text wherever possible. It's great for displaying values to users, but lousy for being confident that you've got the right data without having to be careful about different formats etc.