【发布时间】:2021-08-02 20:55:15
【问题描述】:
我正在尝试使用 Dapper ORM 检索 SQLite 数据库的内容并使用它填充对象列表。但是,即使我已将数据库中的列类型设置为 BLOB,我仍然收到一个错误,这似乎表明 Dapper ORM 正在将数据解释为字符串。
正在使用 Python 脚本填充数据库,该脚本配置的列也设置为 BLOB 类型。在 SQLiteStudio 中,我可以以图像预览的形式查看数据,因此正确的数据在数据库中。
查询数据库的代码:
public List<Thumbnail> ReadAll()
{
var test = _dbConnection.Query<Thumbnail>(
"Select * FROM thumbcache").ToList();
return test;
}
这是我的类定义:
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 是正确的) ,并且显示的图像已损坏/不正确。
类定义:
public class Thumbnail
{
public int id { get; set; }
...
public string cachefile { get; set; }
public string image { get; set; } //Changed this to string
}
我的 C# 的当前输出(从消息框中显示的 db 中直接提取的 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;
}
}
【问题讨论】:
-
sqlite 是...有点有趣的;它主要希望所有内容都是字符串,所以我 猜测 这里的架构声称它是 be 字符串,而 Dapper 根据什么做出了一些错误的选择架构正在声明
-
@MarcGravell 是否有可能让“更了解”的开发者以任何方式“帮助”Dapper 做出更好的选择?
-
@MarcGravell 感谢您的回复。我现在尝试使用 base64 字符串作为数据库中的存储方法,但是在尝试将 base64 转换为图像时遇到了一些奇怪的错误。我已经更新了我的问题以显示这一点。你能看出我做错了什么吗?
-
@Jack Convert.FromBase64String 是解析 base-64 编码负载的正确方法。数据实际上是 base-64 编码的吗?
-
@MarcGravell 是的,它是 base64 编码的,为了确认这一点,我将 base64 保存在数据库中,并通过在线 base64 到图像转换器,结果完美。经过一些调试后,看起来 Dapper 正在用二进制而不是 base64 填充对象......?因此,与其只是从数据库中获取字符串值并将其直接放入字符串类变量中,不如将其从 base64 转换为介于两者之间,然后仍将其存储在字符串中。