首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

基於 .NET 平台的分層架構實戰 (九):數據訪問層第三種實現——NBear ORM 框架

     編輯:關於.NET

ORM 簡介與框架選擇

對象關係映射 (ORM) 連接面向對象開發與關係數據庫。.NET 平台有 NHibernate、NBear 等。本文選用 NBear (Teddy's Knowledge Base 開源框架),含 ORM、IoC、MVP 等組件,此處僅用 ORM。最新版下載:https://files.cnblogs.com/hjf1223/NBearV3.7.2.11_src.rar。

實現步驟

1. 創建實體設計專案

新建 NBearEntityDesign 專案,引用 NBear.Common.Design.dll。新建 EntityDesign.cs 定義實體介面:

public interface TAdmin : Entity {
    [PrimaryKey] int ID { get; }
    [SqlType("nvarchar(20)")] string Name { get; set; }
    [SqlType("nvarchar(50)")] string Password { get; set; }
}
public interface TComment : Entity { ... }
public interface TMessage : Entity { ... }

編譯備用。

2. 生成 NBear 專用實體類與配置

運行 NBear.Tools.EntityDesignToEntity.exe,選擇編譯產出的 DLL,輸出命名空間 NGuestBook.NBearDAL,點「Generate Entities」獲取實體類代碼。新建 NBearDAL 專案,添加 Entities.cs 貼上代碼,引用 NBear.Common.dll、NBear.Data.dll。點「Generate Configuration」獲取配置,新建 Web 專案下 NBearConfig.xml 存放。修改 Web.config:

<configSections>
  <section name="entityConfig" type="NBear.Common.EntityConfigurationSection, NBear.Common"/>
</configSections>
<entityConfig>
  <includes>
    <add key="Sample Entity Config" value="~/NBearConfig.xml"/>
  </includes>
</entityConfig>
<connectionStrings>
  <add name="NBearConnectionString" connectionString="Server=LOCALHOST\SQLEXPRESS;Database=NGuestBook;Uid=WebUser;Pwd=123456" providerName="NBear.Data.SqlServer.SqlDbProvider"/>
</connectionStrings>

3. 編寫轉換器

BLL/表示層用通用實體 (AdminInfo),NBear 需專用實體 (TAdmin)。編寫 AdminConvertor 雙向轉換:

public sealed class AdminConvertor {
    public static TAdmin CommonEntityToNBearEntity(AdminInfo common) { ... }
    public static AdminInfo NBearEntityToCommonEntity(TAdmin nbear) { ... }
}

4. 實現數據訪問層

利用 NBear Gateway 訪問數據庫,以 AdminDAL 為例:

public class AdminDAL : IAdminDAL {
    public bool Insert(AdminInfo admin) {
        Gateway.SetDefaultDatabase("NBearConnectionString");
        var trans = Gateway.Default.BeginTransaction();
        try {
            Gateway.Default.Save<TAdmin>(AdminConvertor.CommonEntityToNBearEntity(admin));
            trans.Commit(); return true;
        } catch { trans.Rollback(); return false; }
        finally { Gateway.Default.CloseTransaction(trans); }
    }
    // Delete、Update、GetByID、GetByNameAndPassword、GetByName、GetAll 類似
    // 查詢用 Gateway.Default.Find/FindArray,配合 Lambda 條件 (TAdmin._.Name == name)
}

NBear 讓 ORM 訪問極其方便,代碼簡潔且強類型。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved