【问题标题】:Entity Framework Code First Text Store as Image in SQL实体框架代码优先文本存储为 SQL 中的图像
【发布时间】:2012-08-17 18:51:08
【问题描述】:

我有一个旧版 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;设置;} ?

【问题讨论】:

    标签: sql entity-framework ef-code-first binary-data


    【解决方案1】:

    解决方案比我想象的要容易。我将在 SQL 中标识为 Image 的内容更改为字节数组 (byte[]),并创建了一个处理 BITS 值的属性 (Specs)。 Entity Framework 很高兴,它可以双向工作。非常简单。

    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);
         }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-02-26
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多