1

我只是徘徊,如果它可以使用流利NHibernate自动映射.Net TcpClient对象?流利NHibernate自动映射

我有一个类,我有一个TcpClient属性,我想映射。

我试着创建一个继承自TcpClient的自定义类,它叫做tTcpClient,并用getter/setter添加一个Id属性;但是,它仍在寻找基类的Id字段。

任何人有任何想法,如果有可能,或者我需要创建我自己的TcpClient的XML映射?

我当时希望能够保存对象,以便在重新加载应用程序时轻松地重新创建对象,并将TcpClient对象的属性绑定到PropertiesGrid并允许通过相当简单的配置。

谢谢。

回答

2

NHibernate的不知道该如何处理复杂的类型,如TcpClient的开箱即用。但它可以让你提供自己的加载和存储代码。您可以使用IUserType

public class TcpClientMapper : IUserType { 

    public SqlType[] SqlTypes { 
     get { 
      return new[] { 
          new SqlType(DbType.String), 
          new SqlType(DbType.Int32) 
         }; 
     } 
    } 

    public Object NullSafeGet(IDataReader rs, String[] names, ...) { 

     String address = NHibernateUtil.String.NullSafeGet(rs, names[0]); 
     Int32 port = NHibernateUtil.Int32.NullSafeGet(rs, names[1]); 

     return new TcpClient(address, port); 
    } 

    public void NullSafeSet(IDbCommand cmd, Object value, Int32 index) { 
     TcpClient tcpClient = value as TcpClient; 
     if(tcpClient == null) { 
      NHibernateUtil.String.NullSafeSet(cmd, null, index); 
      NHibernateUtil.Int32.NullSafeSet(cmd, null, index + 1); 
     } else { 
      EndPoint red = tcpClient.Client.RemoteEndPoint; 
      IPEndPoint endpoint = ((IPEndPoint)red); 
      NHibernateUtil.String.Set(cmd, endpoint.Address.ToString(), index); 
      NHibernateUtil.Int32.Set(cmd, endpoint.Port, index + 1); 
     } 
    } 

    public Type ReturnedType { 
     get { return typeof(TcpClient); } 
    } 

    // TODO: implement other methods 
} 

而且像这样的HBM映射它:

<property name="_tcpClient" type="MyNamespace.TcpClientMapper, MyAssembly"> 
    <column name="Address" /> <!-- NullSafeGet/Set index == 0 --> 
    <column name="Port" />  <!-- NullSafeGet/Set index == 1 --> 
</property> 

或者用流利的UserTypeConvention

public class TcpClientUserTypeConvention : UserTypeConvention<TcpClientMapper> { 
} 
+0

我明白了。我将不得不实施IUserType的所有方法,然后我会假设它为了工作?如果是的话,你将如何实现这个NullSafeSet?我的类中的属性本身仍然是常规的TcpClient权利,还是需要将其更改为ClientMapper类? –

+0

是的,你必须实现所有的方法,这并不难,看看答案中的链接。属性仍然是一个普通的TcpClient(从设计的角度来看这有点奇怪)。请参阅上次编辑NullSafeSet实现。 – Dmitry

+0

这看起来不错,感谢您的帮助。 另一个快速问题?您如何知道发送到字符串[]数组的内容的顺序?我意识到你阅读的属性,但你怎么知道地址在位置0和阵列中的位置1的端口? 我问的原因是B/C我试图实现串行连接相同。 –

1

Nathan,

你看过这个项目吗?

http://automapper.org/

干杯

+0

难道这就像流利的自动映射或某事的功能性质? –

+0

我几乎低估了这是完全偏离主题,但后来意识到你实际上可以使用自动映射器作为解决这个问题的一部分。我会尽快写出详细信息。 –

+0

首先创建一个单独的类,其中包含所有希望NHibernate保存到数据库的数据。然后使用AutoMapper(一种将数据从一个对象复制到另一个对象的工具)将值从持久对象移动到TcpClient实例上。 –