EF核心更新 - 数据库错误“操作数类型冲突:日期与smallint不兼容”

时间:2017-05-23 21:30:10

标签: c# sql sql-server entity-framework

当我尝试将日期时间的列类型更改为smallint时,

EF核心更新 - 数据库失败:“操作数类型冲突:日期与smallint不兼容”

迁移文件:

公共部分类BookYearFieldChanged:迁移

{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AlterColumn<short>(
            name: "Published",
            table: "Books",
            nullable: false,
            oldClrType: typeof(DateTime),
            oldType: "date");
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AlterColumn<DateTime>(
            name: "Published",
            table: "Books",
            type: "date",
            nullable: false,
            oldClrType: typeof(short));
    }
}

1 个答案:

答案 0 :(得分:0)

创建一个具有所需数据类型的新列,使用所需数据更新新列并删除上一列。

CREATE TABLE [dbo].[table1](
	[columr1] [nvarchar](100) NULL,
	[DTime] [datetime] NULL
) 

/*	you can't do like this*/
/*	alter table table1
	alter column Dtime smallint */
 
ALTER TABLE table1 
ADD DTM smallint

UPDATE table1 
SET DTM = CAST(DTime as smallint)

ALTER TABLE table1 
DROP column DTime

sp_rename 'table1.DTM','DTime','column'
GO