0

I have Entity Framework ObjectContext. I need to update column of type datetime.

Here is my code:

ObjectContext.ExecuteStoreCommand(string.Format("update MyTable set DateTimeField='{0}' where Id = {1}",
                                  myEntity.DateTimeField, IdValue));

Why am I getting such exception:

Submit operation failed. The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. The Statement has been terminated.

0

2 Answers 2

4

ObjectContext.ExecuteStoreCommand takes SqlParameters so Its better if you use parameterized query like:

ObjectContext.ExecuteStoreCommand(
    "update MyTable set DateTimeField=@pDateTimeField  where Id = @pID", 
      new SqlParameter {ParameterName = "@pDateTimeField", Value =myEntity.DateTimeField  },
      new SqlParameter {ParameterName = "@pID", Value =IdValue });

See: Working with Parameterized Commands - MSDN

Currently your code is not working because it is considering DateTime as string value.

Sign up to request clarification or add additional context in comments.

2 Comments

+1...just pipped me to it! Assuming myEntity.DateTimeField is a DateTime this should just work
My solution worked out for me but doesn't work on staging. I will check in several minutes..
2

It looks like myEntity.DateTimeField is a string and not a datetime field.

1 Comment

No matter what type it is, after it has come through his code string.Format("some sql '{0}' continue sql", myEntity.DateTimeField), surely it is reduced to a substring of some new string. What that substring looks like depends on what override of ToString() is hit at runtime (virtual method).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.