C# 使用.NET和SQL更新datetime

C# 使用.NET和SQL更新datetime,c#,.net,sql,sql-server,entity-framework,C#,.net,Sql,Sql Server,Entity Framework,我有实体框架ObjectContext。我需要更新datetime类型的列 这是我的密码: ObjectContext.ExecuteStoreCommand(string.Format("update MyTable set DateTimeField='{0}' where Id = {1}", myEntity.DateTimeField, IdValue)); 为什么我会得到这样的例外: 提交操作失败。将varchar

我有实体框架ObjectContext。我需要更新datetime类型的列

这是我的密码:

ObjectContext.ExecuteStoreCommand(string.Format("update MyTable set DateTimeField='{0}' where Id = {1}",
                                  myEntity.DateTimeField, IdValue));
为什么我会得到这样的例外:

提交操作失败。将varchar数据类型转换为datetime数据类型导致值超出范围。声明已终止


看起来myEntity.DateTimeField是一个字符串,而不是datetime字段

看起来myEntity.DateTimeField是一个字符串,而不是datetime字段

接受SqlParameters,因此如果您使用参数化查询(如:

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

当前您的代码不工作,因为它将
DateTime
视为字符串值

接受SqlParameters,因此如果您使用参数化查询(如:

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


当前您的代码不工作,因为它将
DateTime
视为字符串值

+1…只是比我快了一步!假设myEntity.DateTimeField是一个DateTime,这应该可以解决我的解决方案,但不适用于暂存。我会在几分钟后检查..+1…刚刚告诉我了!假设myEntity.DateTimeField是一个DateTime,这应该可以解决我的解决方案,但不适用于暂存。我会在几分钟后检查。无论它是什么类型,在通过他的代码
string.Format(“一些sql'{0}'继续sql”,myEntity.DateTimeField)
之后,它肯定会被缩减为一些新字符串的子字符串。该子字符串的外观取决于在运行时对
ToString()
的重写是什么(
virtual
方法)。无论它是什么类型,在通过他的代码
string.Format(“某些sql'{0}'continue sql”,myEntity.DateTimeField)
之后,它肯定会减少为某个新字符串的子字符串。该子字符串的外观取决于运行时命中的
ToString()
重写(
virtual
方法)。