NHibernate 3 Beginner's Guide

前言

这一章是一个完整的NHibernate的Simple,原文中用Fluent NHibernate做映射,但我使用NHibernate3.2版本,所以3.2的Conformist代替Fluent NHibernate.

从这里我们将学习到使用NHibernate的一般步骤:

1.定义Model

2.映射Model

3.定义配置

4.1根据配置创建数据库

4.2根据配置BuildSessionFactory

5.用SessionFactory对象OpenSession

6.用session对象做数据库操作

1.定义Model

定义两个类Product,Category

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 decimal UnitPrice { get; set; }
    public virtual int ReorderLevel { get; set; }
    public virtual bool Discontinued { get; set; }
    public virtual Category Category { get; set; }
}

类关系图:

2.映射Model

创建两个类CategoryMap,ProductMap

public class ProductMap : ClassMapping<Product>
{
    public ProductMap()
    {
        this.Id(p => p.Id, map =>
        {
            map.Generator(Generators.Identity);
        });
        this.Property(p => p.Description);
        this.Property(p => p.Discontinued);
        this.Property(p => p.Name);
        this.Property(p => p.ReorderLevel);
        this.Property(p => p.UnitPrice);
        this.ManyToOne(p => p.Category);
    }
}

上面主键自动递增,Product的Category属性用ManyToOne映射

3.定义配置

public Form1()
{
    InitializeComponent();

    configuration.DataBaseIntegration(
        x =>
        {
            x.Dialect<SQLiteDialect>();
            x.Driver<SQLite20Driver>();
            x.ConnectionString = connString;
        });

    var mapper = new ModelMapper();
    mapper.AddMapping<ProductMap>();
    mapper.AddMapping<CategoryMap>();
    var hbmMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
    configuration.AddMapping(hbmMapping);
    Debug.WriteLine(hbmMapping.AsString());
}

这里做了几件事,设置数据库方言,数据库驱动,数据库连接字符串,把映射添加到配置中.

Debug.WriteLine输出的xml映射:

4.1根据配置创建数据库

有了配置就可以生成数据库

private void btCreateDataBase_Click(object sender, EventArgs e)
{
    var sc = new SchemaExport(configuration);
    sc.SetOutputFile(@"db.sql").Execute(false, false, false);
    sc.Create(false, true);
}

生成的数据库关系图

4.2根据配置BuildSessionFactory

有了配置就可以BuildSessionFactory

private ISessionFactory CreateSessionFactory()
{
    return configuration.BuildSessionFactory();
}

5.用SessionFactory对象打开Session

有了ISessionFactory 就可以OpenSession

private void btnCreateSession_Click(object sender, EventArgs e)
{
    var factory = CreateSessionFactory();
    using (var session = factory.OpenSession())
    {
        // do something with the session
    }
}

6.用session对象做数据库操作

有了ISession对象,就像做数据库操作,可以把ISession对象想象成对象化的数据库

添加

private void btAddCategory_Click(object sender, EventArgs e)
{
    var factory = CreateSessionFactory();
    using (var session = factory.OpenSession())
    {
        var category = new Category
        {
            Name = txtCategoryName.Text,
            Description = txtCategoryDescription.Text
        };
        var id = session.Save(category);
        MessageBox.Show(id.ToString());
    }
}

查询

private void btLoadAll_Click(object sender, EventArgs e)
{
    var factory = CreateSessionFactory();
    using (var session = factory.OpenSession())
    {
        var categories = session.Query<Category>()
        .OrderBy(c => c.Id)
        .Select(c => c.Name + "-" + c.Description).ToArray();
        lbCategory.DataSource = categories;
    }
}

NHibernate 3 Beginner's Guide

时间: 2024-10-29 02:59:48

NHibernate 3 Beginner's Guide的相关文章

(转)A Beginner&#39;s Guide To Understanding Convolutional Neural Networks Part 2

Adit Deshpande CS Undergrad at UCLA ('19) Blog About A Beginner's Guide To Understanding Convolutional Neural Networks Part 2 Introduction Link to Part 1 In this post, we’ll go into a lot more of the specifics of ConvNets. Disclaimer: Now, I do reali

(转)A Beginner&#39;s Guide To Understanding Convolutional Neural Networks

Adit Deshpande CS Undergrad at UCLA ('19) Blog About A Beginner's Guide To Understanding Convolutional Neural Networks Introduction Convolutional neural networks. Sounds like a weird combination of biology and math with a little CS sprinkled in, but

Beginner&#39;s Guide to Python-新手指导

Refer English Version: http://wiki.python.org/moin/BeginnersGuide New to programming? Python is free, and easy to learn if you know where to start! This guide will help you to get started quickly. 没玩过编程? Python语言是免费的,如果你知道从何处开始,它很容易上手! 本指南将帮助你快速入门. N

(Molehill) Game Programming Beginner&#39;s Guide 读书笔记 chapter2

-- chapter2. //23.-- Blueprint of a MolehillStage3D objects are not inside the DisplayList in Flash!As they are not DisplayObjects, you cannot apply filters or blendmodes. You cannot even put a Stage3D object over the top of other Flash 2D graphics!

Photography theory: a beginner&#39;s guide(telegraph.co.uk)

By Diane Smyth, Tim Clark, Rachel Segal Hamilton and Lewis Bush 11:00AM BST 09 Jun 2014 Have you read the Bible cover to cover? Probably not, but it's also fair to assume you know the basic plot, the central characters and a few choice quotes. This i

A Beginner’s Guide to Recurrent Networks and LSTMs

A Beginner’s Guide to Recurrent Networks and LSTMs Contents Feedforward Networks Recurrent Networks Backpropagation Through Time Vanishing and Exploding Gradients Long Short-Term Memory Units (LSTMs) Capturing Diverse Time Scales Code Sample & Commen

A Beginner&#39;s Guide To Understanding Convolutional Neural Networks(转)

A Beginner's Guide To Understanding Convolutional Neural Networks Introduction Convolutional neural networks. Sounds like a weird combination of biology and math with a little CS sprinkled in, but these networks have been some of the most influential

A Beginner’s Guide to Eigenvectors, PCA, Covariance and Entropy

A Beginner’s Guide to Eigenvectors, PCA, Covariance and Entropy Content: Linear Transformations Principal Component Analysis (PCA) Covariance Matrix Change of Basis Entropy & Information Gain Resources This post introduces eigenvectors and their rela

这书真的不错--Spring MVC Beginner&#39;s Guide

五百多页,我干到三百多页了. 每个知识点都有说明,操作,解释. 学SPRING MVC,有它就够了. 遗憾的是,这个PDF的文档格式太稀松啦,且,无中文版~~~ 我都想作汉化翻译工作了...算了,忍住,先往前走走~~~~~~~ 这书真的不错--Spring MVC Beginner's Guide