首先使用Entity Framework 4,MySQL和代码存储字节数组?

Dyn*_*nde 8 c# mysql entity-framework ef-code-first

嘿,我正在尝试byte[]使用EF 4 MySQL(最新连接器)和代码优先方法存储一个简单的方法.

简单地做:

public byte[] Thumbnail {get; set;}
Run Code Online (Sandbox Code Playgroud)

在创建时给我以下错误:

您的SQL语法有错误; 查看与您的MySQL服务器版本对应的手册,以便在附近使用正确的语法

然后它指出我的byte[]声明之后发生的事情.

有人给我任何快速提示吗?

Sky*_*ula 6

您需要使用MaxLength属性.

[MaxLength(16)]
public byte[] test { get; set; }
Run Code Online (Sandbox Code Playgroud)

请注意,上面将其转换为tinyblob数据类型,可能会出现索引/主键问题.使用迁移时,它变为:

AddColumn("dbo.testDB", "test", c => c.Binary(storeType: "tinyblob"));
Run Code Online (Sandbox Code Playgroud)

如果需要索引/主键,可以使用该属性column并设置TypeName"Binary".

[MaxLength(16), Column(TypeName = "Binary")]
public byte[] test { get; set; }
Run Code Online (Sandbox Code Playgroud)

虽然上面的结果是我的二进制(1)列(这是我如何到达这里).

编辑:要获得正确的长度二进制数组,只需添加(16)后,binary在迁移文件:

AddColumn("dbo.testDB", "test", c => c.Binary(storeType: "binary(16)"));
Run Code Online (Sandbox Code Playgroud)

不幸的是,添加Column属性的typename不起作用.

Edit2:可以通过创建自定义MySqlMigrationSqlGenerator来获取正确的数据库,而无需编辑迁移文件.

internal class CustomMySqlMigrationSqlGenerator : MySqlMigrationSqlGenerator
{
    protected override MigrationStatement Generate(CreateTableOperation op)
    {
        MigrationStatement statement = base.Generate(op);

        foreach (ColumnModel column in op.Columns)
        {
            if (column.MaxLength.HasValue)
            {
                statement.Sql = statement.Sql.Replace($"`{column.Name}` binary", $"`{column.Name}` binary({column.MaxLength.Value})");
            }
        }

        return statement;
    }
}
Run Code Online (Sandbox Code Playgroud)