在NHibernate/SQL Server中自动截断字符串 [英] Automatically truncating strings in NHibernate / SQL Server

查看:83
本文介绍了在NHibernate/SQL Server中自动截断字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SQL Server 2005数据库中有一个nvarchar(2000)列,并将其映射到NHibernate中,如下所示:

I have a nvarchar(2000) column in a SQL Server 2005 database, and have mapped this into NHibernate as:

<property name="Query" column="`Query`" type="String" length="2000" not-null="false"/>

DTO类仅显示一个字符串属性:

The DTO class just presents a string property:

    public virtual string Query { get; set; }

如果我将查询设置为> 2000个字符的字符串,则会从SQL Server获得一个异常,以达到以下效果:

If I set the query to a string of > 2000 characters I get an exception from SQL server to the effect of:

字符串或二进制数据将是 被截断.该声明已经 终止."

"String or binary data would be truncated. The statement has been terminated."

我想要的是这种截断自动且无声地发生.我可以重写虚拟属性,并在属性集上强制截断,但是默认情况下,应该有一种方法可以通过NHibernate映射甚至作为SQL Server设置来实现此行为.

What I want is for this truncation to just happen automatically and silently. I could override the virtual property and force the truncation on the property set, but feel there should be a way to get this behaviour by default, either via the NHibernate mapping or even as a SQL server setting.

我缺少任何内容吗...我不想更改数据库架构以允许更长的字符串.

Am I missing anything ... I don't want to change the db schema to allow longer strings.

推荐答案

创建自定义用户类型,如果该字符串长于2000个字符,则将截断该字符串.这是创建用户类型

Create a custom User Type and which truncates the string if it's longer than 2000 chars. Here is sample of creating User Type

<property name="Query" type="Common.Nhibernate.Types.StringTruncType, Common" column="`Query`" type="String" length="2000" not-null="false"/>

这篇关于在NHibernate/SQL Server中自动截断字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆