2012-01-04 55 views
5

嘿,我嘗試存儲一個簡單的byte[]使用EF 4的MySQL(最新的連接器)和代碼優先方法。使用Entity Framework 4,MySQL和代碼優先存儲字節數組?

簡單地做:

public byte[] Thumbnail {get; set;} 

讓我在創建以下錯誤:

您的SQL語法錯誤;檢查手冊中 對應於你的MySQL服務器版本正確的語法使用 附近

然後它指向我byte[]聲明之後隨之而來的權利。

任何人有對我有什麼小祕訣?

+0

我錯過了什麼?是不是實體框架只與SQL Server兼容? – Yuck 2012-01-04 14:08:22

+0

@Yuck實體框架不僅與SQL Server兼容,你可以看到這裏的列表:http://en.wikipedia.org/wiki/ADO.NET_Entity_Framework#Entity_Framework_ADO.NET_providers – 2012-01-04 15:22:30

+0

但對於代碼首先它是一個更精簡名單 – 2012-01-10 04:38:03

回答

2

您需要使用maxlength屬性。

[MaxLength(16)] 
public byte[] test { get; set; } 

請注意,上述內容將其轉換爲tinyblob數據類型wich can have indexing/primary key problems。當使用遷移會變成這樣:

AddColumn("dbo.testDB", "test", c => c.Binary(storeType: "tinyblob")); 

您可以使用屬性column並設置TypeName"Binary"如果你需要索引/主鍵。

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

雖然上面的結果在我的二進制(1)列(這是我怎麼到這裏)。

編輯:要獲得正確的長度二進制數組,在遷移文件binary後只需添加(16)

AddColumn("dbo.testDB", "test", c => c.Binary(storeType: "binary(16)")); 

不幸的是,將它添加列屬性的類型名稱不起作用。

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; 
    } 
} 
+0

哇... 4歲的職位。呃,我沒有辦法驗證這是正確的,所以我只是要聽取你的意見 – Dynde 2016-02-23 17:21:24

相關問題