使用NHibernate3 Attributes的配置
在使用NHibernate3进行数据库操作时,我们可以使用Attributes来配置实体类和映射关系,这样可以更加直观和简便。 所需的dll文件 在使用NHibernate3 Attributes
在使用NHibernate3进行数据库操作时,我们可以使用Attributes来配置实体类和映射关系,这样可以更加直观和简便。
所需的dll文件
在使用NHibernate3 Attributes的配置之前,需要引用以下几个dll文件:
- NHibernate.dll
配置
在开始配置实体类之前,我们需要先配置文件。该文件中包含了数据库连接信息等相关配置。下面是一个示例配置:
lt;?xml version"1.0" encoding"utf-8"?gt;
lt;hibernate-configuration xmlns"urn:nhibernate-configuration-2.2"gt;
lt;session-factorygt;
lt;property name"">;/property>
lt;property name"_class">;/property>
lt;property name"_string">your_connection_stringlt;/property>
lt;property name"dialect">;/property>
lt;property name"show_sql">truelt;/property>
lt;/session-factorygt;
lt;/hibernate-configurationgt;
编写并初始化代码
接下来,我们需要编写代码来初始化NHibernate的配置和SessionFactory。以下是一个示例代码:
static cfg new ();
static ISessionFactory sessions null;
//配置并打开Session
public static ISession OpenSession()
{
try
{
MemoryStream stream new MemoryStream();
true;
(stream, ());
stream.Position 0;
();
(stream);
();
sessions ().BuildSessionFactory();
}
catch (Exception e)
{
Console.WriteLine();
}
return ();
}
//关闭Session
public static void CloseSession()
{
if (sessions ! null !)
{
();
}
}
实体类attributes配置
在使用NHibernate3 Attributes的配置时,我们需要为每个实体类添加一些attributes来指定映射关系和数据库表结构。以下是一个示例代码:
// 用户信息
[Serializable]
[Class(Table"UserInfo", Name"UserInfo")]
public class UserInfo
{
// 主键
[Id(Name "ID", Column "ID", TypeType typeof(Int64))]
[Key]
[Generator(Class "native")]
public virtual Int64 ID { get; set; }
// 用户名
[Property]
public virtual String Username { get; set; }
// 密码
[Property]
public virtual String Password { get; set; }
// 昵称
[Property]
public virtual String Nikename { get; set; }
}
总结
通过使用NHibernate3 Attributes的配置,我们可以更加直观和简便地定义实体类和映射关系。同时,通过合理配置文件和编写初始化代码,我们可以轻松地使用NHibernate进行数据库操作。