工作中可能会需要用到NHibernate,这东西因为是从java那边传过来的。说实话对于.Net程序员的我是有些排斥的。
简单的使用Asp.net Core 来做一个NHibernate的配置步骤。
这里我先默认你已经有了一个.NetCore项目。
那么首先就是添加引用了。
通过命令后在项目根目录使用dotnet从nuget上直接引用
dotnet add package NHibernate.NetCore
然后我们可以在创建一个实体模型放你自己喜欢的位置吧。我这里是放在了Models
直接用官方教程里面的
http://nhibernate.info/doc/tutorials/first-nh-app/your-first-nhibernate-based-application.html
using System;
namespace FirstSolution.Domain
{
public class Product
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public bool Discontinued { get; set; }
}
}
然后可以创建个文件夹放映射文件,这里就假设文件夹名字叫Mappings
<?xml version="1.0" encoding="UTF-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="项目命名空间"
namespace="项目命名空间.实体模型命名空间">
<!-- more mapping info here -->
<class name="Product">
<id name="Id">
<generator class="guid" />
</id>
<property name="Name" />
<property name="Category" />
<property name="Discontinued" />
</class>
</hibernate-mapping>
接下来就是一个NHibernate的数据库访问配置文件
嗯,官网有一个可以下载的引用文件压缩包里面带了很多数据库的对应配置文件。 写博客的时候版本是5.1.3下载解压后找到Configuration_Templates,挑选自己需要的数据库访问文件,我觉得直接拷贝到项目根目录就行。
http://sourceforge.net/projects/nhibernate/files/NHibernate/5.1.3/NHibernate-5.1.3-bin.zip/download
完成了数据库配置文件以后那么我们就打开Startup.cs
先添加引用
using NHibernate.NetCore;
然后在Startup.cs里面找到ConfigureServices方法在这个方法里面添加代码
// nhibernate 配置文件的路径
var path = System.IO.Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"hibernate.cfg.xml"
);
// 添加 NHibernate 相关的服务
services.AddHibernate(path);
这里的hibernate.cfg.xml文件放到了项目根本目录的数据库链接配置文件
接下来我们打开csproj项目文件
<ItemGroup>
<Folder Include="Mappings\" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Mappings/*.hbm.xml" />
</ItemGroup>
<ItemGroup>
<Content Update="hibernate.cfg.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
这里的Content Update我发现是没用的,我觉得还是最好复制一份文件到bin/debug/运行版本里面 /
启动起来如果没有出错应该就说明没问题了。
以下是基本的增删改查代码。
说实话这么一圈下来感觉真的很java.
using (ISession session = NHibernateHelper.OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(new Product(){Name="测试", Category="123",Discontinued=false});
session.Get<Product>("");
session.Delete(new Product());
session.Update(new Product());
IList<Product> list = session.CreateCriteria(typeof(Product)).Add(Restrictions.Eq("Name", 123)).List<Product>();
transaction.Commit();
}