如何将byte[]值映射到SQL类型的Image



我有以下接口:

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呢?或者我可以用不同的方式存储图像?

谢谢。

您应该将new SqlDataRecord(..)放在foreach语句中,否则它将始终返回相同的对象,并且只覆盖这些值。不确定你是如何使用它的,但这可能是个问题。

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

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

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

最新更新