从 EntityFramework v6 插入/更新到 SqlServer.Date 列
Insert / Update into SqlServer.Date column from EntityFramework v6
注意:这是一个 Sql 服务器日期数据类型(不是 DateTime,也不是 DateTime2,大多数答案似乎都关注它)。
如何从 EF 插入?
我试过如下,但我卡在.NET端。
TB_MyTable newEntity = new TB_MyTable()
{
col1 = "abc",
col2 = 123
dtCol = DateTime.MinValue,
dateOnlyCol = ??? What goes here, range is '0001-01-01' to '9999-12-31'
};
TB_MyTable inserted = dbCtx.TB_MyTable.Add(newEntity);
int rowsAffected = dbCtx.SaveChanges();
.SaveChanges() 的错误是:
{"The conversion of a datetime2 data type to a datetime data type
resulted in an out-of-range value.\r\nThe statement has been
terminated."}
请不要建议我在右侧使用字符串,它不起作用:P
dtCol
列的数据类型是什么?
错误似乎表明它是 datetime
(最小值 1/1/1753),而您正试图将年份 0001 (DateTime.MinValue
) 插入其中。
另外
Microsoft 推荐 DATETIME2
而不是 DATETIME
。对于新项目,我建议您使用 DATETIME2
,尤其是为了更顺畅的 .NET 集成。
更多详情:DateTime2 vs DateTime in SQL Server
注意:这是一个 Sql 服务器日期数据类型(不是 DateTime,也不是 DateTime2,大多数答案似乎都关注它)。
如何从 EF 插入?
我试过如下,但我卡在.NET端。
TB_MyTable newEntity = new TB_MyTable()
{
col1 = "abc",
col2 = 123
dtCol = DateTime.MinValue,
dateOnlyCol = ??? What goes here, range is '0001-01-01' to '9999-12-31'
};
TB_MyTable inserted = dbCtx.TB_MyTable.Add(newEntity);
int rowsAffected = dbCtx.SaveChanges();
.SaveChanges() 的错误是:
{"The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\nThe statement has been terminated."}
请不要建议我在右侧使用字符串,它不起作用:P
dtCol
列的数据类型是什么?
错误似乎表明它是 datetime
(最小值 1/1/1753),而您正试图将年份 0001 (DateTime.MinValue
) 插入其中。
另外
Microsoft 推荐 DATETIME2
而不是 DATETIME
。对于新项目,我建议您使用 DATETIME2
,尤其是为了更顺畅的 .NET 集成。
更多详情:DateTime2 vs DateTime in SQL Server