Question

I changed the data type of a field in my model from string to byte array and I got this error when I run Update-Database code first migration method.

Implicit conversion from data type nvarchar(max) to varbinary(max) is not allowed. Use the CONVERT function to run this query

What is the solution?

thanks

Was it helpful?

Solution

SQL Server can't directly change a string to a binary, so its asking that you convert the data. With respect to Code First Migrations, I would drop the AlterColumn statements from the DbMigration, and instead manually write:

AddColumn("dbo.TableName", "ColumnNameTmp", c => c.Binary());
Sql("Update dbo.TableName SET ColumnNameTmp = Convert(varbinary, ColumnName)");
DropColumn("dbo.TableName", "ColumnName");
RenameColumn("dbo.TableName", "ColumnNameTmp", "ColumnName")

And the reverse in the Down method, if desired. (the above is pseudocode, forgive any syntax errors)

OTHER TIPS

It can not change to column data type, Just try to delete or comment the column from your model add migration and update database, and in the second step add the column with byte[] data type and add migration igen. unfortunately if you hade any data in that column you will lose them.

    public class ExampleModel
{
    [Key]
    public int Id { get; set; }
    public string Code { get; set; }
}

comment the column and add migration and update database

    public class ExampleModel
{
   [Key]
   public int Id { get; set; }
   //public string Code { get; set; }
}

and then add the column with byte[] data type

    public class ExampleModel
{
    [Key]
    public int Id { get; set; }
    public Byte[] Code { get; set; }
}

and now add migration and then update database.

alter TABLE [dbo].[ETABLISSEMENT_SANTES] ADD [ETS_LOGO_TMP] varbinary NULL; alter TABLE [dbo].[ETABLISSEMENT_SANTES] DROP COLUMN [ETS_LOGO]; EXEC sp_rename '[dbo].[ETABLISSEMENT_SANTES].ETS_LOGO_TMP', 'ETS_LOGO';

protected override void Up(MigrationBuilder migrationBuilder) {migrationBuilder.DropColumn("Password", "Users"); migrationBuilder.AddColumn<byte[]>( name: "Password", table: "Users", type: "varbinary(max)", nullable: false /* oldClrType: typeof(string), oldType: "nvarchar(max)"*/ ); } //Update-Database or dotnet ef database update

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top