2012-08-17 54 views
0

我有一個傳統SQL數據庫,它有一個鏈接表來存儲訂單行的規格。應用程序設計人員使用SQL中的圖像字段將文本存儲爲二進制數據。我嘲笑了下面的例子:實體框架代碼首先將文本存儲爲SQL中的圖像

public class OrderLine 
{ 
    public int ID { get; set; } 
    public int OrderID { get; set; } 
    public int LineNo { get; set; } 
    public string Product { get; set; } 
    public decimal Quantity { get; set; } 
    public decimal UnitPrice { get; set; } 
    public string Status { get; set; } 
} 

public class OrderLineSpecifications 
{ 
    public int ID { get; set; } 
    public int OrderID { get; set; } 
    public int OrderLineNo { get; set; } 
    public Image Bits { get; set; } // <--- This Line 
    public int Bit_Length { get; set; } 
} 

SQL表定義

[ID] [int] IDENTITY(1,1) NOT NULL, 
    [OrderID] [varchar](15) NOT NULL, 
    [OrderLineNo] [smallint] NOT NULL, 
    [Bits] [image] NULL, 
    [Bit_Length] [int] NOT NULL 

目前我必須使用SQL與

cast(cast(Bits as varbinary(max)) as varchar(max)) 

提取文本,然後進行反向恢復它到數據庫。是否可以在EF中完成轉換?也許在物業層面{get;設置;}?

回答

0

解決方案比我想象的要容易。我將SQL中標識爲Image的內容更改爲字節數組(byte []),並創建了處理BITS值的屬性(Specs)。實體框架很高興,它可以在兩個方向上工作。令人驚訝的容易。

public virtual byte[] BITS { get; set; } 
public virtual int BITS_LENGTH { get; set; } 
[NotMapped] 
public virtual string Specs 
{ 
    get 
    { 
     UTF8Encoding enc = new UTF8Encoding(); 
     string str = enc.GetString(BITS); 
     return str; 
    } 
    set 
    { 
     UTF8Encoding encoding = new UTF8Encoding(); 
     BITS = encoding.GetBytes(value); 
    } 

}