刚刚接触NHibernate和FluentNHibernate,所以最好的方法是从一个简单的例子入手。

开发环境考虑到是实际情况还有好多朋友没有用VS2015,就用VS2013withUpdate5吧。

1.创建Asp.net Web应用程序(MVC),叫FluentNHibernateDemo1

选择Empty,MVC

2.管理NuGet程序包

添加FluentNHibernate,2.0.3.0

添加bootstrap

添加jquery.validate.unobtrusive

添加JQuery validation with bootstrap

3.添加Model

public class Item
{
[Key]
public virtual int Id { get; set; }
[Display(Name = "姓名")]
[Required(ErrorMessage = "姓名必须")]
public virtual string Name { get; set; }
[Display(Name = "年龄")]
[Required(ErrorMessage = "年龄必须")]
public virtual int Age { get; set; }
[Display(Name = "描述")]
public virtual string Description { get; set; }
}

4.添加Map,注意这里使用C#完成映射

public class ItemMap:ClassMap<Item>
{
public ItemMap()
{
Table("Item");
Id(m => m.Id).GeneratedBy.Native();
Map(m => m.Name).Length(50).Not.Nullable();
Map(m => m.Age).Not.Nullable();
Map(m => m.Description).Length(500);
}
}

5.添加NHibernate help类

public class NHibernateHelper
{
private const string exportFilePath = @"c:\abc.sql";
public static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(MsSqlConfiguration
.MsSql2008
.ConnectionString(c => c.FromConnectionStringWithKey("DefaultConnection")))
.Mappings(m => m.FluentMappings
.AddFromAssemblyOf<ItemMap>()).ExposeConfiguration(CreateSchema)
.BuildSessionFactory();
}
private static void CreateSchema(Configuration cfg)
{
var schemaExport = new SchemaExport(cfg);
var str = cfg.Properties["connection.connection_string"].ToString();
bool isNew = isNewDb(str);
if (isNew)
{
if (System.IO.File.Exists(exportFilePath))
System.IO.File.Delete(exportFilePath);
schemaExport.SetOutputFile(exportFilePath);
}
schemaExport.Create(false, isNew);
} private static bool isNewDb(string connectString)
{
bool isNew = false;
try
{
using (SqlConnection conn = new SqlConnection(connectString))
{
conn.Open();
string sql = "select * FROM Item";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteReader(CommandBehavior.CloseConnection);
} }
catch
{
isNew = true;
}
return isNew;
}
}

这里要解释一下:

a)

ConnectionString(c => c.FromConnectionStringWithKey("DefaultConnection")))

是指在web.config中配置在web.config

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\Demo.mdf;Initial Catalog=test;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>

我采用的是Vs2013自带的localdb,数据库名为Demo.mdf,所以我先要建一个空的数据库(Demo.mdf),至于表,我会用CodeFirst生成。

b)

bool isNew = isNewDb(str);
schemaExport.Create(false, isNew);

原因是当数据库为空是我们要用schemaExport.Create(false, true);

这时会生成数据库

当数据库存在表时,我们要用schemaExport.Create(false, false);

如果是schemaExport.Create(false, true);会出现无法新增数据的情况

6.新建Home Controller

Controller 代码:

public class HomeController : Controller
{
public ActionResult Create()
{
return View();
}
public ActionResult Edit(int id)
{
var factory = NHibernateHelper.CreateSessionFactory();
using (var session = factory.OpenSession())
{
IList<Item> items = session.CreateCriteria(typeof(Item))
.Add(Restrictions.Eq("Id", id))
.List<Item>();
var result = items.Count > ? items[] : null;
return View(result);
}
}
[HttpPost]
public ActionResult Edit(Item item)
{
if (ModelState.IsValid)
{
var factory = NHibernateHelper.CreateSessionFactory();
using (var session = factory.OpenSession())
{ session.Update(item, item.Id);
session.Flush();
}
}
return RedirectToAction("Index");
}
public ActionResult DeleteConfirm(int id)
{
var factory = NHibernateHelper.CreateSessionFactory();
using (var session = factory.OpenSession())
{
// IList<Item> items = session.CreateCriteria(typeof(Item))
// .Add(Restrictions.Eq("Id", id))
// .List<Item>();
// var result = items.Count > 0 ? items[0] : null;
// if (result != null)
// session.Delete(result);
session.Delete("From Item where Id=" + id);
session.Flush();
return RedirectToAction("Index");
}
}
public ActionResult Delete(int id)
{
var factory = NHibernateHelper.CreateSessionFactory();
using (var session = factory.OpenSession())
{
var result = session.Get<Item>(id);
return View(result);
}
} [HttpPost]
public ActionResult Create(Item item)
{
if (ModelState.IsValid)
{
var factory = NHibernateHelper.CreateSessionFactory();
using (var session = factory.OpenSession())
{ session.Save(item);
session.Flush();
}
}
return RedirectToAction("Index");
}
// GET: Home
public ActionResult Index()
{
var factory = NHibernateHelper.CreateSessionFactory();
IEnumerable<Item> items;
using (var session = factory.OpenSession())
{
items = session.CreateQuery("from Item").List<Item>();
}
return View(items);
}
}

7.View代码

Views\Home\Create.cshtml

 @model IEnumerable<FluentNHibernateDemo1.Models.Item>

 @{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th></th>
</tr> @foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
} </table>
</body>
</html>

Index.cshtml

 <!DOCTYPE html>

 <html>
<head>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<meta name="viewport" content="width=device-width" />
<title>Create</title>
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
</head>
<body> @using (Html.BeginForm())
{
@Html.AntiForgeryToken() <div class="form-horizontal">
<h4>Item</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
} <div>
@Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>

Create.cshtml

 @model FluentNHibernateDemo1.Models.Item

 @{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> <title>Edit</title>
</head>
<body> @using (Html.BeginForm())
{
@Html.AntiForgeryToken() <div class="form-horizontal">
<h4>Item</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id) <div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
} <div>
@Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>

Edit.cshtml

 @model FluentNHibernateDemo1.Models.Item

 @{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<title>Delete</title>
</head>
<body>
<div>
<h4>Item</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Name)
</dt> <dd>
@Html.DisplayFor(model => model.Name)
</dd> <dt>
@Html.DisplayNameFor(model => model.Age)
</dt> <dd>
@Html.DisplayFor(model => model.Age)
</dd> <dt>
@Html.DisplayNameFor(model => model.Description)
</dt> <dd>
@Html.DisplayFor(model => model.Description)
</dd> </dl>
</div>
<p>
@Html.ActionLink("Delete", "DeleteConfirm", new { id = Model.Id }) |
@Html.ActionLink("Back to List", "Index")
</p>
</body>
</html>

Delete.cshtml

8.好了,在chrome中运行正常

Index

Create

Edit

附上完整代码:

http://pan.baidu.com/s/1sloW1M9

密码: 9zhr

本人第一个例子,有不足之处欢迎指正

  

最新文章

  1. asp.net(C#)读取文件夹和子文件夹下所有文件,绑定到GRIDVIEW并排序 .
  2. [SHTSC 2014] 信号增幅仪
  3. #mysql:command not found
  4. 巧用loadrunner代理,录制手机APP脚本
  5. PHP debug 环境配置
  6. inheritableStatics 与statics类
  7. HDU 5145 NPY and girls 莫队+逆元
  8. Sina App Engine(SAE)入门教程(2)-Mysql使用
  9. 关于Spring中AOP的理解
  10. SpringMVC入门二: 1规范结构, 2简单整合MyBatis
  11. &lt;Mastering KVM Virtualization&gt;:第四章 使用libvirt创建你的第一台虚拟机
  12. PLSQL锁表之后改如何操作
  13. 使用FFMPeg对视频进行处理
  14. Android ROM开发(二)——ROM架构以及Updater-Script脚本分析,常见的Status错误解决办法
  15. Ubantu更新hostname &amp; hosts
  16. vue 上实现无缝滚动播放文字系统公告
  17. TestFlight 的使用记载
  18. Ubuntu安装lrzsz
  19. POJ-3078.Shuffle&#39;m Up(简单模拟题)
  20. iTerm通过堡垒机自动登录服务器

热门文章

  1. ACM: FZU 2107 Hua Rong Dao - DFS - 暴力
  2. Java技巧(代码简略)
  3. bzoj1720: [Usaco2006 Jan]Corral the Cows 奶牛围栏
  4. html5新特性
  5. git 常见问题
  6. 隐藏ASP.NET站点的HTTP Headers
  7. 从程序员到CTO的Java技术路线图(我爱分享)
  8. 【java学习笔记】字符串和Date的转换
  9. CSP -- 运营商内容劫持(广告)的终结者
  10. iOS应用程序生命周期(前后台切换,应用的各种状态)详解