我一直希望NHibernate能夠支持像EF一樣支持可視化操作,今天去網上搜了一下,發現有一個插件,類似EF的可視化功能。
下載地址:Mindscape.NHibernateModelDesigner_crack.vsix
下載后,運行Mindscape.NHibernateModelDesigner_crack.vsix,進行安裝,安裝完成之后,在新建項目的時候,就會發現多了如下模版:
用過EF的朋友應該很熟悉,這個界面就跟EF的可視化界面非常相似了。
打開服務器資源管理器,然后連接到Northwind數據庫
拖放之后,將會自動生成如下類
我們來看下這個生成的類的源碼

using System; using System.Collections.Generic; using NHibernate.Cfg; using NHibernate.Validator.Constraints; namespace Shop.Domain { [System.CodeDom.Compiler.GeneratedCode("NHibernateModelGenerator", "1.0.0.0")] public partial class Customer { [NotNull] [Length(Max=5)] public virtual string CustomerId { get; set; } [NotNull] [Length(Max=40)] public virtual string CompanyName { get; set; } [Length(Max=30)] public virtual string ContactName { get; set; } [Length(Max=30)] public virtual string ContactTitle { get; set; } [Length(Max=60)] public virtual string Address { get; set; } [Length(Max=15)] public virtual string City { get; set; } [Length(Max=15)] public virtual string Region { get; set; } [Length(Max=10)] public virtual string PostalCode { get; set; } [Length(Max=15)] public virtual string Country { get; set; } [Length(Max=24)] public virtual string Phone { get; set; } [Length(Max=24)] public virtual string Fax { get; set; } private IList<Order> _orders = new List<Order>(); public virtual IList<Order> Orders { get { return _orders; } set { _orders = value; } } static partial void CustomizeMappingDocument(System.Xml.Linq.XDocument mappingDocument); internal static System.Xml.Linq.XDocument MappingXml { get { var mappingDocument = System.Xml.Linq.XDocument.Parse(@"<?xml version='1.0' encoding='utf-8' ?> <hibernate-mapping xmlns='urn:nhibernate-mapping-2.2' assembly='" + typeof(Customer).Assembly.GetName().Name + @"' namespace='Shop.Domain' > <class name='Customer' table='`Customers`' > <id name='CustomerId' column='`CustomerID`' > <generator class='identity'> </generator> </id> <property name='CompanyName' column='`CompanyName`' /> <property name='ContactName' column='`ContactName`' /> <property name='ContactTitle' column='`ContactTitle`' /> <property name='Address' column='`Address`' /> <property name='City' column='`City`' /> <property name='Region' column='`Region`' /> <property name='PostalCode' column='`PostalCode`' /> <property name='Country' column='`Country`' /> <property name='Phone' column='`Phone`' /> <property name='Fax' column='`Fax`' /> <bag name='Orders' inverse='false' > <key column='`CustomerID`' /> <one-to-many class='Order' /> </bag> </class> </hibernate-mapping>"); CustomizeMappingDocument(mappingDocument); return mappingDocument; } } } }
這個類當中包含了生成的model類和xml映射文件
這里我只是簡單的介紹存在這樣一個插件,這個差件自動生成了我們需要的映射類和配置文件,以及數據庫配置文件,以及NHibenate輔助類,有了這些東西,我們就可以很方便的進行開發了,只要Ctrl+C,Ctrl+V。具體的使用方法,大家可以去參考上一篇:Hibernate學習筆記—使用 NHibernate構建一個ASP.NET MVC應用程序