ena*_*rik 1 sql-server-2000 backwards-compatibility ef-migrations entity-framework-4.3
当我试图通过EF迁移使我的数据库版本化时,我收到错误"从字符串转换日期和/或时间时转换失败".问题是我的MS Sql Server版本(带有高级服务的Microsoft SQL Server Express Edition)不支持EF生成的日期字符串('2012-03-21T18:23:13.525Z')用于新的迁移脚本条目(64-位)).这是一个错误吗?有工作吗?
CREATE TABLE [__MigrationHistory] (
[MigrationId] [nvarchar](255) NOT NULL,
[CreatedOn] [datetime] NOT NULL,
[Model] [varbinary](max) NOT NULL,
[ProductVersion] [nvarchar](32) NOT NULL,
CONSTRAINT [PK___MigrationHistory] PRIMARY KEY ([MigrationId])
)
BEGIN TRY
EXEC sp_MS_marksystemobject '__MigrationHistory'
END TRY
BEGIN CATCH
END CATCH
INSERT INTO [__MigrationHistory] ([MigrationId], [CreatedOn], [Model], [ProductVersion])
VALUES ('201203210144184_init', '2012-03-21T18:23:13.525Z', 0x33, '4.3.1');
Run Code Online (Sandbox Code Playgroud)
编辑
没关系.这与EntityFramework无关.如果我的SQL Server数据库配置为向后兼容SQL Server 2000,它将不接受该日期格式.我想除非我可以让EF以另一种格式输出它的日期字符串(或者让SQL Server向后兼容到2000并仍然理解EF日期字符串),我将无法在我的数据库中使用EF迁移: - (.如果有人找到了将EF与兼容级别为SQL Server 2000的数据库一起使用的方法,请告诉我.
如果您仍想传递Date,则可以将defaultSqlValueoptional参数与有效的SQL DateTime一起使用.例如:
public partial class AddTransactionDate : DbMigration
{
public override void Up()
{
// defaultValueSql is where the magic happens.
AddColumn("dbo.StorageTransaction", "Created", c => c.DateTime(nullable: false, defaultValueSql: DateTimeToSql(DateTime.UtcNow)));
}
public override void Down()
{
DropColumn("dbo.StorageTransaction", "Created");
}
private static string DateTimeToSql(DateTime dt)
{
// Use the .Net SqlDateTime class to create a valid
// SQL server DATETIME. We also need to wrap it in quotes
// because EF prints out your values verbatim (e.g. you could
// also use GETUTCDATE() etc.).
return string.Format("N'{0}'",
new System.Data.SqlTypes.SqlDateTime(dt).ToSqlString());
}
}
Run Code Online (Sandbox Code Playgroud)
瞧:
ALTER TABLE [dbo].[StorageTransaction] ADD [Created] [datetime] NOT NULL DEFAULT N'2012-11-26 03:06:09 PM'
INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])
VALUES ('201211261300214_AddTransactionDate', 'Symblr.Migrations.Configuration',
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1680 次 |
| 最近记录: |