我的第一個FluentNHibernate例子

来源:http://www.cnblogs.com/conan77/archive/2016/04/10/5373480.html
-Advertisement-
Play Games

剛剛接觸NHibernate和FluentNHibernate,所以最好的方法是從一個簡單的例子入手。 開發環境考慮到是實際情況還有好多朋友沒有用VS2015,就用VS2013withUpdate5吧。 1.創建Asp.net Web應用程式(MVC),叫FluentNHibernateDemo1 ...


剛剛接觸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 > 0 ? items[0] : 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);
    }
}
View Code

 7.View代碼

Views\Home\Create.cshtml

 1 @model IEnumerable<FluentNHibernateDemo1.Models.Item>
 2 
 3 @{
 4     Layout = null;
 5 }
 6 
 7 <!DOCTYPE html>
 8 
 9 <html>
10 <head>
11     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
12     <meta name="viewport" content="width=device-width" />
13     <title>Index</title>
14 </head>
15 <body>
16     <p>
17         @Html.ActionLink("Create New", "Create")
18     </p>
19     <table class="table">
20         <tr>
21             <th>
22                 @Html.DisplayNameFor(model => model.Name)
23             </th>
24             <th>
25                 @Html.DisplayNameFor(model => model.Age)
26             </th>
27             <th>
28                 @Html.DisplayNameFor(model => model.Description)
29             </th>
30             <th></th>
31         </tr>
32     
33     @foreach (var item in Model) {
34         <tr>
35             <td>
36                 @Html.DisplayFor(modelItem => item.Name)
37             </td>
38             <td>
39                 @Html.DisplayFor(modelItem => item.Age)
40             </td>
41             <td>
42                 @Html.DisplayFor(modelItem => item.Description)
43             </td>
44             <td>
45                 @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
46                 @Html.ActionLink("Delete", "Delete", new { id=item.Id })
47             </td>
48         </tr>
49     }
50     
51     </table>
52 </body>
53 </html>
Index.cshtml
 1 <!DOCTYPE html>
 2 
 3 <html>
 4 <head>
 5     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
 6     <meta name="viewport" content="width=device-width" />
 7     <title>Create</title>
 8     <script src="~/Scripts/jquery-1.9.1.min.js"></script>
 9     <script src="~/Scripts/jquery.validate.min.js"></script>
10     <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
11 </head>
12 <body>
13     
14     
15     @using (Html.BeginForm()) 
16     {
17         @Html.AntiForgeryToken()
18         
19         <div class="form-horizontal">
20             <h4>Item</h4>
21             <hr />
22             @Html.ValidationSummary(true, "", new { @class = "text-danger" })
23             <div class="form-group">
24                 @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
25                 <div class="col-md-10">
26                     @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
27                     @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
28                 </div>
29             </div>
30     
31             <div class="form-group">
32                 @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
33                 <div class="col-md-10">
34                     @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
35                     @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
36                 </div>
37             </div>
38     
39             <div class="form-group">
40                 @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
41                 <div class="col-md-10">
42                     @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
43                     @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
44                 </div>
45             </div>
46     
47             <div class="form-group">
48                 <div class="col-md-offset-2 col-md-10">
49                     <input type="submit" value="Create" class="btn btn-default" />
50                 </div>
51             </div>
52         </div>
53     }
54     
55     <div>
56         @Html.ActionLink("Back to List", "Index")
57     </div>
58 </body>
59 </html>
Create.cshtml
 1 @model FluentNHibernateDemo1.Models.Item
 2 
 3 @{
 4     Layout = null;
 5 }
 6 
 7 <!DOCTYPE html>
 8 
 9 <html>
10 <head>
11     <meta name="viewport" content="width=device-width" />
12     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
13     <script src="~/Scripts/jquery-1.9.1.min.js"></script>
14     <script src="~/Scripts/jquery.validate.min.js"></script>
15     <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
16 
17     <title>Edit</title>
18 </head>
19 <body>
20 
21 
22     @using (Html.BeginForm())
23     {
24         @Html.AntiForgeryToken()
25 
26         <div class="form-horizontal">
27             <h4>Item</h4>
28             <hr />
29             @Html.ValidationSummary(true, "", new { @class = "text-danger" })
30             @Html.HiddenFor(model => model.Id)
31 
32             <div class="form-group">
33                 @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
34                 <div class="col-md-10">
35                     @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
36                     @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
37                 </div>
38             </div>
39 
40             <div class="form-group">
41                 @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
42                 <div class="col-md-10">
43                     @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
44                     @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
45                 </div>
46             </div>
47 
48             <div class="form-group">
49                 @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
50                 <div class="col-md-10">
51                     @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
52                     @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
53                 </div>
54             </div>
55 
56             <div class="form-group">
57                 <div class="col-md-offset-2 col-md-10">
58                     <input type="submit" value="Save" class="btn btn-default" />
59                 </div>
60             </div>
61         </div>
62     }
63 
64     <div>
65         @Html.ActionLink("Back to List", "Index")
66     </div>
67 </body>
68 </html>
Edit.cshtml
 1 @model FluentNHibernateDemo1.Models.Item
 2 
 3 @{
 4     Layout = null;
 5 }
 6 
 7 <!DOCTYPE html>
 8 
 9 <html>
10 <head>
11     <meta name="viewport" content="width=device-width" />
12     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
13     <title>Delete</title>
14 </head>
15 <body>
16     <div>
17         <h4>Item</h4>
18         <hr />
19         <dl class="dl-horizontal">
20             <dt>
21                 @Html.DisplayNameFor(model => model.Name)
22             </dt>
23     
24             <dd>
25                 @Html.DisplayFor(model => model.Name)
26             </dd>
27     
28             <dt>
29                 @Html.DisplayNameFor(model => model.Age)
30             </dt>
31     
32             <dd>
33                 @Html.DisplayFor(model => model.Age)
34             </dd>
35     
36             <dt>
37                 @Html.DisplayNameFor(model => model.Description)
38             </dt>
39     
40             <dd>
41                 @Html.DisplayFor(model => model.Description)
42             </dd>
43     
44         </dl>
45     </div>
46     <p>
47         @Html.ActionLink("Delete", "DeleteConfirm", new { id = Model.Id }) |
48         @Html.ActionLink("Back to List", "Index")
49     </p>
50 </body>
51 </html>
Delete.cshtml

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

Index

 

 

Create

Edit

附上完整代碼:

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

密碼: 9zhr

本人第一個例子,有不足之處歡迎指正

  


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 2個集合合併,有相同的只取中其一個: source code: ...
  • 找到兩個集合中交集部分: source code: ...
  • 在兩個集合中,左邊集合減去右邊集合的元素: source code: ...
  • Modern UI WPF包括兩個內置主題(dark與light)。在1.0.3版本,您可以構建自定義的主題。Modern UI應用程式通常有在全局資源字典App.xaml中有如下定義: “/FirstFloor.ModernUI;component/Assets/ModernUI.xaml”字典包... ...
  • 目錄 1.倉儲模式在MVC應用程式中的使用 2.泛型倉儲模式在MVC應用程式中的使用 3.MVC Code-First和倉儲模式的應用 4.待續.... 附上源代碼:https://github.com/caofangsheng93/CaoDanDeGit 這篇文章中,我會解釋倉儲模式在MVC程式中 ...
  • Modern UI for WPF帶有一個內置的頁面導航框架,易於使用和可擴展的。但這並不是必須的,你也可以自己來自定義一個導航框架。 預設的ModernWindow控制項模板包括標題、菜單和後退控制項用於支持頁面導航框架。在預設模板中ModernWindow.Content屬性將被忽略而且不會被渲染。... ...
  • asp.net MVC請求過程 ASP.NET MVC框架只是給開發者提供了開發web應用程式的一種選擇,並不是要取代Webform這兩種技術各有優缺點,開發者需要根據實際情況,選擇對應的技術有時候,可以在同一個項目中混合使用這兩種技術 WebForm請求過程 個人網站:http://www.51p ...
  • SqlBulkCopy原理是採用了SQL Server的BCP協議進行數據的批量複製,結合使用事務,就我們的案例而言,大約每批800條是平衡點,性能比逐條插入提高了100多倍,並前面同樣使用事務批量插入的案例性能提升了7倍以上。 個人網站:http://www.51pansou.com .net視頻 ...
一周排行
    -Advertisement-
    Play Games
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...
  • 目錄前言PostgreSql安裝測試額外Nuget安裝Person.cs模擬運行Navicate連postgresql解決方案Garnet為什麼要選擇Garnet而不是RedisRedis不再開源Windows版的Redis是由微軟維護的Windows Redis版本老舊,後續可能不再更新Garne ...
  • C#TMS系統代碼-聯表報表學習 領導被裁了之後很快就有人上任了,幾乎是無縫銜接,很難讓我不想到這早就決定好了。我的職責沒有任何變化。感受下來這個系統封裝程度很高,我只要會調用方法就行。這個系統交付之後不會有太多問題,更多應該是做小需求,有大的開發任務應該也是第二期的事,嗯?怎麼感覺我變成運維了?而 ...
  • 我在隨筆《EAV模型(實體-屬性-值)的設計和低代碼的處理方案(1)》中介紹了一些基本的EAV模型設計知識和基於Winform場景下低代碼(或者說無代碼)的一些實現思路,在本篇隨筆中,我們來分析一下這種針對通用業務,且只需定義就能構建業務模塊存儲和界面的解決方案,其中的數據查詢處理的操作。 ...
  • 對某個遠程伺服器啟用和設置NTP服務(Windows系統) 打開註冊表 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer 將 Enabled 的值設置為 1,這將啟用NTP伺服器功 ...
  • title: Django信號與擴展:深入理解與實踐 date: 2024/5/15 22:40:52 updated: 2024/5/15 22:40:52 categories: 後端開發 tags: Django 信號 松耦合 觀察者 擴展 安全 性能 第一部分:Django信號基礎 Djan ...
  • 使用xadmin2遇到的問題&解決 環境配置: 使用的模塊版本: 關聯的包 Django 3.2.15 mysqlclient 2.2.4 xadmin 2.0.1 django-crispy-forms >= 1.6.0 django-import-export >= 0.5.1 django-r ...
  • 今天我打算整點兒不一樣的內容,通過之前學習的TransformerMap和LazyMap鏈,想搞點不一樣的,所以我關註了另外一條鏈DefaultedMap鏈,主要調用鏈為: 調用鏈詳細描述: ObjectInputStream.readObject() DefaultedMap.readObject ...
  • 後端應用級開發者該如何擁抱 AI GC?就是在這樣的一個大的浪潮下,我們的傳統的應用級開發者。我們該如何選擇職業或者是如何去快速轉型,跟上這樣的一個行業的一個浪潮? 0 AI金字塔模型 越往上它的整個難度就是職業機會也好,或者說是整個的這個運作也好,它的難度會越大,然後越往下機會就會越多,所以這是一 ...
  • @Autowired是Spring框架提供的註解,@Resource是Java EE 5規範提供的註解。 @Autowired預設按照類型自動裝配,而@Resource預設按照名稱自動裝配。 @Autowired支持@Qualifier註解來指定裝配哪一個具有相同類型的bean,而@Resourc... ...