使用 dapper 从 SQLite 数据库中检索二进制数据

Retrieve binary data from SQLite database with dapper

我正在尝试使用 Dapper ORM 检索 SQLite 数据库的内容并使用它填充对象列表。但是,即使我已将数据库中的列类型设置为 BLOB,我还是收到一个错误,这似乎表明 Dapper ORM 正在将数据解释为字符串。

正在使用 Python 脚本填充数据库,该脚本配置的列也设置为 BLOB 类型。在 SQLiteStudio 中,我可以将数据作为图像预览查看,因此正确的数据在数据库中。

错误:

查询数据库的代码:

public List<Thumbnail> ReadAll()
{
    var test = _dbConnection.Query<Thumbnail>(
                "Select * FROM thumbcache").ToList();       
    return test;
}

这是我的 class 定义:

public class Thumbnail
{
    public int id { get; set; }
    public DateTime scantime { get; set; }
    public int imageheight { get; set; }
    public int imagewidth { get; set; }
    public string identifier { get; set; }
    public long offset { get; set; }
    public string signature { get; set; }
    public int entrySize { get; set; }
    public int identifierlen { get; set; }
    public long datasize { get; set; }
    public int paddingsize { get; set; }
    public string datachecksum { get; set; }
    public string headerchecksum { get; set; }
    public string entryhash { get; set; }
    public string cachefile { get; set; }
    public byte[] image { get; set; }   // This is the field that fails to be populated
}

数据库中的数据:

任何人都可以发现我在这里做错了什么吗?如果您有任何建议,我将不胜感激。

为了回应@MarcGravell 的评论,我现在尝试将二进制文件保存为数据库中的 base64 并使用 C# 对其进行解析,但是我发现大多数图像都抛出无效的 base64 错误(即使数据库中的 base64 是正确),显示的图像是 corrupt/incorrect.

Class定义:

public class Thumbnail
{
    public int id { get; set; }
    ...
    public string cachefile { get; set; }
    public string image { get; set; }   //Changed this to string
}

我的 C# 的当前输出(消息框中显示的直接从数据库中提取的 base64 字符串的值):

有趣的是,MessageBox 应该显示从数据库中提取的 base64,但它似乎显示的是字节?

然后用在线工具直接将数据库中的base64转成图片是这样的:

我创建图像的代码:

private Image create_image(Thumbnail thumb)
{
    string imageBase64 = thumb.image;
    MessageBox.Show(imageBase64);
    try
    {
        byte[] imageBytes = Convert.FromBase64String(imageBase64)
        using (MemoryStream ms = new MemoryStream(imageBytes))
        {
            Image image = Image.FromStream(ms);
            return image;
        }
    }
    catch
    {
        return null;
    }
}

这是我在不使用 try-catch 时得到的错误:

我已经从使用 Dapper 转移到 SQLite-Net 来解决这个问题。

https://github.com/praeclarum/sqlite-net/

不确定 Dapper 的问题是什么;我数据库中的数据始终正确显示,所以我只能假设 Dapper 在从数据库中提取数据并填充对象时一定对数据做了一些奇怪的事情。

我坚持对二进制数据使用 Base64 编码,我没有用原始二进制数据测试 SQLite-Net。