带有 byte[] 参数的 NHibernate ISQLQuery 抛出错误

标签 nhibernate fluent-nhibernate arrays isqlquery

因此,我正在尝试使用 nhibernate 来调用保存图像的存储过程。我的问题是查询失败并出现此错误:

The length of the byte[] value exceeds the length configured in the mapping/parameter.

这是我将参数附加到 ISQLQuery 的地方.参数是一个 Dictionary<string, object> .

public void Execute()
{

    string sql = BuildSprocDefinition();
    var query = Session.CreateSQLQuery(sql);

    foreach (var parameter in Parameters)
    {
        if (parameter.Value is int)
            query.SetParameter<int>(parameter.Key, (int)parameter.Value);
        else if (parameter.Value is long)
            query.SetParameter<long>(parameter.Key, (long)parameter.Value);
        else if (parameter.Value is bool)
            query.SetParameter<bool>(parameter.Key, (bool)parameter.Value);
        else if (parameter.Value is byte[])
            query.SetBinary(parameter.Key, (byte[])parameter.Value);
        else
            query.SetParameter(parameter.Key, parameter.Value);
    }

    using (var tx = Session.BeginTransaction())
    {
        query.ExecuteUpdate();
        Session.Flush();
        tx.Commit();
    }
}

protected string BuildSprocDefinition()
{
    StringBuilder sql = new StringBuilder(String.Format("exec {0} ", storedProcName));

    foreach (var parameter in Parameters)
    {
        sql.Append(String.Format(":{0}, ", parameter.Key));
    }

    if (sql.ToString().EndsWith(", "))
    {
        sql = sql.Remove(sql.Length - 2, 2);
    }

    return sql.ToString();
}

在数据库中,我的参数类型是varbinary(max)我正在尝试发送一个“byte[]”作为数据。

我尝试使用特定的 SetBinary然而这失败了。所有其他数据类型似乎都有效。

我也试过query.SetParameter<byte[]>(parameter.Key, (byte[])parameter.Value);有同样的错误。

最佳答案

这是一个有点老的问题,但我把我的答案留给新的搜索者。

对于 byte[] 参数你可以这样指定长度

query.SetParameter(parameter.Key, parameter.Value, NHibernate.Type.TypeFactory.GetBinaryType(((byte[])parameter.Value).Length));

你需要确保过程参数有足够的长度

关于带有 byte[] 参数的 NHibernate ISQLQuery 抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12373698/

相关文章:

c# - 使用 Critieria API 在 NHibernate 中选择子查询

c# - 将整数列表映射到 nHibernate 实体

nhibernate - 将 Nhibernate.Search 与 Nhibernate 2 集成

c# - 流畅的nhibernate级联删除到已连接子类的集合

fluent-nhibernate - 非空字段的 Fluent Nhibernate Automap 约定

java - JDBC - 将数组变量插入到 PostgreSQL 表中

c# - 如何获取 NHibernate 中的预计属性?

entity-framework - EF Fluent 中的 Reference( Fluent nhibernate) 等效项是什么?

c - 结构内部数组的声明有时会失败

arrays - 当源表只有一行时,使用 MATCH 的数组公式不会给出结果