Skip to main content
 首页 » 编程设计

c#之在 Fluent NHibernate 中自动截断字符串

2024年02月20日23jyk

首先,我阅读了this article , this one和 this one ,但我还有一个问题。所以我需要一个具体的 C# 解决方案来解决使用以下任何解决方案截断的问题:IUserType、拦截或 ValidationDef .我想像这样声明字段:

public class MyEntity { 
    [Truncate(length=255)] 
    public virtual string Comments { get; set; } 
} 

我需要在更新/保存 NHibernate 操作之前自动截断字符串行。在这种情况下,我不会得到一个异常(exception) System.Data.SqlClient.SqlErrorCollection

String or binary data would be truncated

请您参考如下方法:

老实说,最简单、最易读的解决方案是让类处理它。像这样:

public class MyEntity { 
  private string comments; 
  public virtual string Comments {  
    get {return comments;}   
    set {comments = str.Substring(0, Math.Min(value.Length, 255))};  
   } 
} 

但我认为这不是您要问的。除此之外,您可以使用具有多种方法(如 OnSave)的 IInterceptor 来做一些事情。您需要为该方法编写类似这样的内容(注意这是 Psudo 代码,因为它有很多东西!):

    public boolean OnSave(object entity, 
                          object id, 
                          object[] state, 
                          string[] propertyNames, 
                          IType[] types) 
    { 
 
            for ( int i=0; i<propertyNames.Length; i++ ) 
            { 
                if ( objectHasAttributeOnproperty(propertyNames[i], Truncate)) 
                { 
                    trucate(entity, propertyNames[i]) 
                    return true; 
                } 
            } 
 
        return true; 
    } 

然后向休眠 session 注册拦截器。保存的每个实体都将通过它并检查需要截断的字符串。

这是 NHibernate 中拦截器的文档: http://www.nhforge.org/doc/nh/en/index.html#manipulatingdata-interceptors

检查堆栈溢出以获取属性值并通过反射调用属性 setter 。