c# - TEXT 字段中的错误 (PostgreSQL) - NHibernate 无法读取它

标签 c# postgresql nhibernate blob

我有这个实体:

public class Product
{
    public virtual long ID { get; set; }
    public virtual string Name { get; set; }
    public virtual string Description { get; set; }
    public virtual ProductCategory Category { get; set; }
    public virtual byte[] Image { get; set; }
    public virtual string IsAvaliableToSell { get; set; }
    public virtual DateTime InsertDate { get; set; }
    public virtual DateTime UpdateDate { get; set; }
}

使用这个 Map 类:

public ProductMapping()
{
    [...]
    Map(model => model.Image, "fldProductImage")
        .Insert()
        .Update()
        .Nullable()
        .CustomType("Text");
    [...]
 }

当我尝试检索添加到数据库中的产品时,出现错误:

Unable to cast object of type 'System.String' to type 'System.Byte []'.

我认为它在我的图像属性中。有谁知道发生了什么事吗?

最佳答案

原因的可能解释是 text 类型有一些 bytea 没有的限制和要求:

  • text 无法存储空字节,因为系统使用以空结尾的字符串;如果您提交字节字符串 abcd\x00efgh(其中 \x00 是空字节),数据库将存储 abcd

  • text 要求数据在客户端的文本编码中有效。当从客户端发送到服务器时,数据被解释为 client_encoding 并在需要时转换为服务器的文本编码。如果不需要转换,它仍然经过验证。

因此,如果您将一堆字节塞进文本字符串中,您将收到截断的乱码。如果您的客户端使用不同的编码,您也可能会因为编码转换问题而在获取数据时出错。

bytea 不关心数据的编码是什么,因为它只是服务器的原始字节。不执行任何转换。因为它是以转义形式发送的,所以它可以包含空字节。您应该始终将二进制数据存储为 bytea 或使用大对象(请参阅 lo 扩展)。唯一的另一种选择是将其存储为一些文本安全表示形式,如 base64 ,但这在 bytea 字段上很少可取。

关于c# - TEXT 字段中的错误 (PostgreSQL) - NHibernate 无法读取它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16175670/

相关文章:

NHibernate 2.1.0.4000 似乎不喜欢批量插入

c# - 替换 PL/SQL 中的特殊 XML 字符

c# - 如何生成唯一的 12 位字母数字 key 以用于 URL

r - 将 dplyr 查询保存到 postgresql

sql - 在 Postgres 的索引处的 SELECT 上插入数组

sql - PSQL 每 10 分钟选择 1 条记录

nhibernate - 如何在使用 NHibernate 进行任何插入之前增加 ID

c# - 与 NHibernate 和 Criteria 联合?

c# - 将字符串从数组转换为 int

c# - 如何检查MediaElement是否已停止?