0

I am using EF6 with SQL Server/SQL Azure with C# and MVC5

I am trying to do something like:

            string insertFeatureCmd = String.Format("INSERT INTO TABLE (Name,Value, DateActivated) " + "VALUES ('{0}','{1}','{2}')", name,value, DateTime.Now);
            db.ExecuteStoreCommand(insertFeatureCmd);

What is the correct syntax for handling the Date Value? Is it '{2}' or {2}. Also do I need to do something with DateTime.Now ie DateTime.Now.ToString() or "DateTime.Now.ToLongDateString()" or something?

Thanks.

EDIT

I get the following SQL generated from my C#. Question is what to do with that data value?

  INSERT INTO TABLE (Name,Value,DateActivated) VALUES ('Name','Value',07/04/2019 02:39:24)

EDIT2

This does not work. I get an exception:

  INSERT INTO TABLE (Name,Value,DateActivated) VALUES ('Name','Value','07/04/2019 02:39:24')

EDIT3: In response to suggested alternative answer. My solution that I went with was, inspired by link, but was:

new SqlParameter("@sinceDateTime", myDate)
SamJolly
  • 6,347
  • 13
  • 59
  • 125
  • 1
    Do you get an error when you run this? The trick is to ensure that a _date_ data type is used throughout. You should never get confused with converting to strings or special formats. I take it `DateActivated` (the database field) is a date or datetime data type? – Nick.Mc Apr 07 '19 at 01:32
  • Yes, it is datetime. Just trying without quotes and .ToString() etc. – SamJolly Apr 07 '19 at 01:36
  • 2
    When you already usign EF, why do you create your query by hand? Use the framework: `dbContext.Table.Add(new Table {})`. Also never concat your sql command with string functions (e.g. sql injection). Use parameters instead. – Christian Gollhardt Apr 07 '19 at 01:54
  • Thanks, I am using parameters, as shown in the top insert command. I am having to use DQL directly due to performance problems with .AddObject. It is much more performant this way. – SamJolly Apr 07 '19 at 01:57
  • 2
    With parameters I mean [`SqlParameter`](https://stackoverflow.com/a/7505842/2441442) and **not** `string.Format` parameters. That said, you probably should ask about the performance problems – Christian Gollhardt Apr 07 '19 at 01:59
  • Any thoughts on what the correct syntax looks like to deal with the date value? – SamJolly Apr 07 '19 at 02:02
  • 2
    Parameterize your query, and you answered the question ;) – Christian Gollhardt Apr 07 '19 at 02:03
  • 1
    Possible duplicate of [How to pass datetime from c# to sql correctly?](https://stackoverflow.com/questions/6570621/how-to-pass-datetime-from-c-sharp-to-sql-correctly) – Christian Gollhardt Apr 07 '19 at 02:05

0 Answers0