引言:Nibernate概述
NHibernate是一个ORM框架,NHibernate是一个把C#对象世界和关系世界数据库之间联系起来的一座桥梁。NHibernate 能自动映射实体模型到数据库,所以这能让你集中考虑一件或多件事情。
1.给Program.cs文件添加代码
注意:以下程序仅供参考,不作为运行的依据。由于本文过旧,所以你必须从控制台进行安装,安装命令为: install-package NHibernate -version 2.1.2.4000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NHibernate.Cfg;
using NHibernate;
using System.Reflection; namespace NHibernatePets
{
public class Pet
{
virtual public int id { get; set; }
virtual public string PetName { get; set; }
virtual public string Species { get; set; }
virtual public DateTime Birthday { get; set; } virtual public string Speak()
{
return "你好!我的名字是 " + PetName + ",我是一个" + Species + " 以及我生日是" + Birthday;
} } public class Program
{
public static void Main(string[] args)
{
Pet peter = new Pet { PetName="peter",Species="Cat",Birthday=new DateTime(,,)};
Console.WriteLine(peter.Speak()); //把peter保存到数据库里面去
try
{
using (ISession session = OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(peter);
transaction.Commit();
}
Console.WriteLine("peter已经保存到数据库!");
} //从数据库里读取peter
using (ISession session = OpenSession())
{
IQuery query = session.CreateQuery("From Pet");
IList<Pet> pets = query.List<Pet>();
Console.Out.WriteLine("宠物的个数:" + pets.Count);
pets.ToList().ForEach(p => Console.WriteLine(p.Speak()));
} //更新宠物信息
using (ISession session = OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
IQuery query = session.CreateQuery("From Pet where PetName='peter'");
Pet pet = query.List<Pet>()[];
pet.PetName="Jason";
transaction.Commit();
}
} //再次从数据库里读取所有的信息
using (ISession session = OpenSession())
{
IQuery query = session.CreateQuery("From Pet");
IList<Pet> pets = query.List<Pet>();
Console.Out.WriteLine("宠物的个数:" + pets.Count);
pets.ToList().ForEach(p => Console.WriteLine(p.Speak()));
} //删除宠物信息
using (ISession session = OpenSession())
{
using (ITransaction transation = session.BeginTransaction())
{
IQuery query = session.CreateQuery("From Pet where PetName='Jason'");
Pet pet = query.List<Pet>()[];
session.Delete(pet);
transation.Commit();
} } }
catch (Exception e)
{
Console.WriteLine(e);
} } static ISessionFactory SessionFactory;
static ISession OpenSession()
{
//注意这种方式不是线程安全的
//SessionFactory会话费大量的资源,只创建一次
if (SessionFactory == null)
{
Configuration configuration = new Configuration();
configuration.AddAssembly(Assembly.GetCallingAssembly());
SessionFactory = configuration.BuildSessionFactory();
} return SessionFactory.OpenSession();
} }
}