如何将带有 ORMlite 的 byte[] 数组插入到图像列中

And*_*eas -7 c# sql-server servicestack ormlite-servicestack

我的网络服务的一个子任务是在数据库中保存文件(以及一些元数据)。
Web服务基于ServiceStack及其ORMlite版本。

所以我创建了一个代表数据库中附件的小类:

public class Attachment {
    public string Description { get; set; }
    public string FileName { get; set; }
    public string Type { get; set; }
    public byte[] Data { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是实际文件

MemoryStream ms = new MemoryStream(webclient.DownloadData(...));
byte[] data = new byte[...];
ms.Read(data, 0, data.Length);

Attachment file = new Attachment() {
    /* all the other stuff */
    Data = data
};
Run Code Online (Sandbox Code Playgroud)

直到现在都没有问题... :)

现在我拥有了将这个文件放入数据库所需的一切。所以让我们开始吧......

dbCmd.Insert<Attachment>(file);
Run Code Online (Sandbox Code Playgroud)


还有问题...

SqlException: "Operand type clash: text is incompatible with image"
Run Code Online (Sandbox Code Playgroud)


ORMlite将字节数组转化为base64编码的字符串

SqlException: "Operand type clash: text is incompatible with image"
Run Code Online (Sandbox Code Playgroud)


我已经搜索了一整天,但没有找到改变 ORMlite 处理byte[]数组方式的解决方案。没有属性DatabaseField,我可以用它来设置dataTypeBYTE_ARRAY,因为它是可以在Java中。

/* stripped-down example of the command string */
INSERT INTO Attachment (Data) VALUES ('CgoKCgoKCjxodG1sPgo8a...AAAA==')
Run Code Online (Sandbox Code Playgroud)


我错过了一些重要的东西吗?
有没有其他方法可以将文件放入数据库?

Gra*_*ray 5

所以,我认为你是在混淆之间ServiceStack的ORMLite内部ORMLite了Java ORM库-他们是不相关的,也没有必要兼容。

您可能会问如何使用 C# ORMLite 读取 Java ORMLite 写入的数据。我完全没有 C# 方面的经验,但我可以谈谈 ORMLite 在这里做什么:

@DatabaseField(dataType = DataType.BYTE_ARRAY)
byte[] imageBytes;
Run Code Online (Sandbox Code Playgroud)

在 SqlServer 中,这应该对应于以下字段:

"bytes" IMAGE
Run Code Online (Sandbox Code Playgroud)

传递给 JDBC 的 SQL 插入命令是:

 INSERT INTO "bytearray" ("bytes" ) VALUES (?)
 insert arguments: [[B@34883357] (byte[])
Run Code Online (Sandbox Code Playgroud)

byte[]从结果中检索results.getBytes(columnPos)

你提到:

ORMlite将字节数组转化为base64编码的字符串

这是 JDBC 这样做的。我很惊讶它确实如此,但我想这是可能的。

希望这里有帮助。