【问题标题】:How can i map a byte[] value to SQL type Image?如何将 byte[] 值映射到 SQL 类型的 Image?
【发布时间】:2016-04-20 10:11:31
【问题描述】:

我有如下界面:

IEnumerator<SqlDataRecord> IEnumerable<SqlDataRecord>.GetEnumerator() 
{
    var SQLRow = new SqlDataRecord(
        new SqlMetaData("id", SqlDbType.BigInt),
        new SqlMetaData("image", SqlDbType.Image));

    foreach (ImageModel item in this)
    {
        SQLRow.SetSqlInt64(0, item.Id);
        // here is the problem (this is a byte[] variable)
        SQLRow.SetSqlByte(1, item.Image); 

        yield return SQLRow;
    }
}

那么我如何将byte[] 映射到Image?或者也许我可以以不同的方式存储图像?

谢谢。

【问题讨论】:

    标签: c# sql


    【解决方案1】:

    您应该将new SqlDataRecord(..) 放在foreach 语句中,否则它将一直返回相同的对象并覆盖值。不知道你如何使用它,但它可能是个问题。

    要设置值,请使用SQLRow.SetSqlBytes(1, new SqlBytes(...));SQLRow.SetSqlBinary(...) or SQLRow.SetBytes(...)

    最好使用varbinary(max)varbinary(YOUR MAX LENGTH) 类型来存储数据,因为image 类型在MS SQL 中已过时。

    【讨论】:

      【解决方案2】:

      您可以将字节数组按原样保存在 SQL Server 中。这样更容易在您的应用程序中检索。

      【讨论】:

      • 好的。性能问题怎么样。如果我将它保存为 NVARCHAR(MAX)Image 有什么缺点?
      • 使用 byte[] 将比 nvarchar(max) 产生性能提升。nvarchar 用于支持不同编码的字符串。对于您的情况,您可以参考帖子stackoverflow.com/questions/25400555/…
      猜你喜欢
      • 2012-08-28
      • 2021-06-27
      • 2014-12-26
      • 1970-01-01
      • 2016-09-29
      • 1970-01-01
      • 2019-04-09
      • 2013-05-30
      • 2018-09-19
      相关资源
      最近更新 更多