环境:
  Visual Studio 2010
一、Mindscape.NhibernateModelDesigner安装
  在打开VS2010之后,我们能够在“工具”菜单下找到“扩展管理器,搜索:Mindscape NHibernate Model Designer 下载安装就可以。安装完毕后,在向项目中加入新项时假设我们拉到最下方我们会看到例如以下界面:
更加详细的操作能够參考:用好VS2010扩展管理器-NHibernate生成
二、依据数据库表结构生成实体并通过实体进行操作
1、加入nhmodel实体
2、打开nhmodel实体,依据数据库表生成实体
  左側工具栏部分切换到【server资源管理器】,连接上你想要获取数据结构的数据库。就会看到展示出来的数据库内容:
  拖动你想要的表到设计器主界面。例如以下图:
就可以获取到数据库表相应的实体。
3、生成配置文件
小注:
  假设不生成配置文件直接执行第4步中代码,会报出以下的错误:
未处理 NHibernate.Cfg.HibernateConfigExceptionHResult=-2146232832Message=An exception occurred during configuration of persistence layer.Source=NHibernateStackTrace:在 NHibernate.Cfg.ConfigurationSchema.HibernateConfiguration..ctor(XmlReader hbConfigurationReader, Boolean fromAppSetting)在 NHibernate.Cfg.ConfigurationSchema.HibernateConfiguration..ctor(XmlReader hbConfigurationReader)在 NHibernate.Cfg.Configuration.Configure(XmlReader textReader)在 NHibernate.Cfg.Configuration.Configure(String fileName, Boolean ignoreSessionFactoryConfig)在 NHibernate.Cfg.Configuration.Configure(String fileName)在 NHibernate.Cfg.Configuration.Configure()在 DataBaseToEntity.ConfigurationHelper.CreateConfiguration() 位置 C:\Users\JianKunKing\Desktop\NHibernateStudy\NHibernateStudy\DataBaseToEntity\NHibernateModel1.cs:行号 20在 DataBaseToEntity.DataBaseToEntityForm1..ctor() 位置 C:\Users\JianKunKing\Desktop\NHibernateStudy\NHibernateStudy\DataBaseToEntity\DataBaseToEntityForm1.cs:行号 20在 DataBaseToEntity.Program.Main() 位置 C:\Users\JianKunKing\Desktop\NHibernateStudy\NHibernateStudy\DataBaseToEntity\Program.cs:行号 18在 System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)在 System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()在 System.Threading.ThreadHelper.ThreadStart_Context(Object state)在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)在 System.Threading.ThreadHelper.ThreadStart()InnerException: System.IO.FileNotFoundExceptionHResult=-2147024894Message=未能找到文件“C:\Users\JianKunKing\Desktop\NHibernateStudy\NHibernateStudy\DataBaseToEntity\bin\Debug\hibernate.cfg.xml”。
Source=mscorlib FileName=C:\Users\JianKunKing\Desktop\NHibernateStudy\NHibernateStudy\DataBaseToEntity\bin\Debug\hibernate.cfg.xml StackTrace: 在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) 在 System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) 在 System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize) 在 System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy) 在 System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn) 在 System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver) 在 System.Threading.CompressedStack.runTryCode(Object userData) 在 System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) 在 System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state) 在 System.Xml.XmlTextReaderImpl.OpenUrl() 在 System.Xml.XmlTextReaderImpl.Read() 在 System.Xml.XmlTextReader.Read() 在 System.Xml.XmlCharCheckingReader.Read() 在 System.Xml.XsdValidatingReader.Read() 在 System.Xml.XPath.XPathDocument.LoadFromReader(XmlReader reader, XmlSpace space) 在 System.Xml.XPath.XPathDocument..ctor(XmlReader reader, XmlSpace space) 在 System.Xml.XPath.XPathDocument..ctor(XmlReader reader) 在 NHibernate.Cfg.ConfigurationSchema.HibernateConfiguration..ctor(XmlReader hbConfigurationReader, Boolean fromAppSetting) InnerException:
4、通过实体来操作数据库:
//获取映射关系及配置
ISessionFactory sessionFactory = ConfigurationHelper.CreateConfiguration().Configure().BuildSessionFactory();
//此处新增
TbNHibernate entity = new TbNHibernate();entity.UserName = "UserName1";entity.UserPwd = "UserPwd1";using (ISession session = sessionFactory.OpenSession()){try{var a = session.Save(entity);session.Flush();}catch (Exception ee){MessageBox.Show(ee.ToString());}}
//部分字段更新
using (ISession session = sessionFactory.OpenSession()){ITransaction trans = session.BeginTransaction();try{string sql = " update tb_NHibernate set userPWD=" + value + " where id='" + id + "'";ISQLQuery Query = session.CreateSQLQuery(sql).AddEntity(typeof(TbNHibernate));Query.ExecuteUpdate();session.Flush();trans.Commit();}catch (Exception ex){MessageBox.Show(ex.ToString());IsSuccess = false;trans.Rollback();}finally{if (session != null){session.Clear();}}}
三、依据实体生成数据库表结构并通过实体进行操作
两者之间的操作与之前一样
小注:
  
1、假设在选择主键生成方式的时候选择了HiLo选项
,那么生成表的主键字段是uniqueidentifier类型的:
CREATE TABLE [dbo].[DataBaseToEntity1](
[Id] [uniqueidentifier] NOT NULL,
[Name] [nvarchar](max) NOT NULL,
[Code] [nvarchar](max) NOT NULL,
PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
  假设在主键类型你选择的是Guid
  那么此时。你实体类中的主键字段是Guid类型的,假设你通过Guid.NewGuid()给你主键字段赋值会报出例如以下错误:
------------------------------------------------------
NHibernate.HibernateException: error performing isolated work ---> System.FormatException: GUID 应包括带 4 个短划线的 32 位数(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)。在 System.Guid.TryParseGuidWithNoStyle(String guidString, GuidResult& result)在 System.Guid.TryParseGuid(String g, GuidStyles flags, GuidResult& result)在 System.Guid..ctor(String g)在 NHibernate.Type.GuidType.Get(IDataReader rs, Int32 index)在 NHibernate.Id.TableGenerator.DoWorkInCurrentTransaction(ISessionImplementor session, IDbConnection conn, IDbTransaction transaction在 NHibernate.Engine.TransactionHelper.Work.DoWork(IDbConnection connection, IDbTransaction transaction)在 NHibernate.Transaction.AdoNetTransactionFactory.ExecuteWorkInIsolation(ISessionImplementor session, IIsolatedWork work, Boolean transacted)--- 内部异常堆栈跟踪的结尾 ---在 NHibernate.Transaction.AdoNetTransactionFactory.ExecuteWorkInIsolation(ISessionImplementor session, IIsolatedWork work, Boolean transacted)在 NHibernate.Transaction.AdoNetWithDistributedTransactionFactory.ExecuteWorkInIsolation(ISessionImplementor session, IIsolatedWork work, Boolean transacted)在 NHibernate.Engine.Transaction.Isolater.DoIsolatedWork(IIsolatedWork work, ISessionImplementor session)在 NHibernate.Engine.TransactionHelper.DoWorkInNewTransaction(ISessionImplementor session)在 NHibernate.Id.TableGenerator.Generate(ISessionImplementor session, Object obj)在 NHibernate.Id.TableHiLoGenerator.Generate(ISessionImplementor session, Object obj)在 NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)在 NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event)在 NHibernate.Event.Default.DefaultSaveEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event)在 NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent event)在 NHibernate.Event.Default.DefaultSaveEventListener.PerformSaveOrUpdate(SaveOrUpdateEvent event)在 NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event)在 NHibernate.Impl.SessionImpl.FireSave(SaveOrUpdateEvent event)在 NHibernate.Impl.SessionImpl.Save(Object obj)在 DataBaseToEntity.DataBaseToEntityForm1.button1_Click(Object sender, EventArgs e) 位置 C:\Users\JianKunKing\Desktop\NHibernateStudy\NHibernateStudy\DataBaseToEntity\DataBaseToEntityForm1.cs:行号 31
---------------------------
确定
---------------------------
  那么这样的情况应该处理呢?毕竟大多数的主键都是Guid类型的啊,此时须要改动你模型主键的生成规则:
在这里改动为guid类型的就能够了
2、选择主键的类型选择int类型的时候:
  此时通过实体操作数据是不须要填充主键字段的,你填充了也更新不进去。
  本文中有什么不正确的地方欢迎支出,谢谢
四、[NHibernate操作文档及demo]
(http://download.csdn.net/detail/xunzaosiyecao/9398186)
作者:jiankunking 出处:http://blog.csdn.net/jiankunking