NHibernate+SQLite学习笔记(一)使用FluentNHibernate映射数据库中的表
参考James.Ying FluentNhibernate 之旅(5) 使用AutoMapping 进行简单开发
1、建立所需表的类:
public class Category { public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual string Description { get; set; } } public class Product { public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual string Description { get; set; } public virtual Category Category { get; set; } public virtual decimal UnitPrice { get; set; } public virtual int RecorderLevel { get; set; } public virtual bool Discontinued { get; set; } }
2、使用FluentNhibernate映射类
public class CategoryMap :ClassMap<Category> { public CategoryMap() { Id(x => x.Id); Map(x => x.Name); Map(x => x.Description); } } public class ProductMap : ClassMap<Product> { public ProductMap() { Id(x => x.Id); Map(x => x.Name); Map(x => x.Description); Map(x => x.UnitPrice); Map(x => x.RecorderLevel); Map(x => x.Discontinued); References(x => x.Category); } }
3、映射语句
3.1 使用数据库SQL server 2012
//操作Nhibernate using FluentNHibernate.Cfg; using FluentNHibernate.Cfg.Db; using NHibernate.Cfg; using NHibernate.Tool.hbm2ddl; public partial class MainWindow : Window { //*********************连接SQL Server 数据库***************************// const string connString = "server=ZGC-20140217VFE;" + "database=NH3BeginnersGuide;" + "Integrated Security=SSPI;"; public MainWindow() { InitializeComponent(); } //***************************// private static void CreateSchema(Configuration cfg) { var schemaExport = new SchemaExport(cfg); schemaExport.Drop(false, true); schemaExport.Create(false, true); } //*************创建一个按钮事件**********************************// private void btnCreateDatabase_Click(object sender,RoutedEventArgs e) { //*********************创建SQL Server 数据库***************************// Fluently.Configure() .Database(MsSqlConfiguration .MsSql2012 .ConnectionString(connString)) .Mappings(m => m.FluentMappings .AddFromAssemblyOf<ProductMap>()) .ExposeConfiguration(CreateSchema) .BuildConfiguration(); } }
3.2 使用SQLite 数据库
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnCreateDatabase_Click(object sender,RoutedEventArgs e)
{
//*********************连接SQLite数据库***************************//
string datasource = "NH3BeginnersGuide.db";
SQLiteConnection.CreateFile(datasource);
//*********************创建SQLite数据库表格********************************//
Fluently.Configure().Database(SQLiteConfiguration.Standard.UsingFile(datasource))
.Mappings(m => m.FluentMappings
.AddFromAssemblyOf<ProductMap>())
.ExposeConfiguration(CreateSchema)
.BuildConfiguration();
}
private static void CreateSchema(Configuration cfg)
{
var schemaExport = new SchemaExport(cfg);
schemaExport.Drop(false, true);
schemaExport.Create(false, true);
}
}
由于我对Nhibernate很多东西不是很理解,只是想使用它进行简单的开发,因此有很多疑问。如果有不当的地方等我理解之后会进行相应的修改。暂时程序是通的(开发环境 VS2013,SQL Serve 2012,SQLite1.0.94.1)

浙公网安备 33010602011771号