1. 程式人生 > 資料庫 >Abp.NHibernate連線PostgreSQl資料庫的方法

Abp.NHibernate連線PostgreSQl資料庫的方法

Abp.NHibernate動態庫連線PostgreSQl資料庫,供大家參考,具體內容如下

初次接觸Abp框架,其框架中封裝的操作各類資料的方法還是很好用的,本人還在進一步的學習當中,並將利用abp.NHibernate類庫操作PostgreSQL資料的相關方法做一記錄,不足之處讓評論指點扔磚。

話不多說,直接開幹:

1、vs 新建一個專案,(窗體或者控制檯程式或者測試程式)

2、NuGet 獲取類庫(adp.NHibernate)

還需安裝一個pgSQl 對應的驅動

3、新建一個繼承AbpModule的類,用於配置資料庫連線資訊和實體對映的相關資訊

using System.Reflection;
using Abp.Configuration.Startup;
using Abp.Modules;
using Abp.NHibernate;
using FluentNHibernate.Cfg.Db;

/**
* 名稱空間: abpPgtest
* 功 能: 配置資料庫
* 類 名: NhHibernateModel
* 作 者: 東騰
* 時 間: 2018/1/29 17:04:27 
*/
namespace abpPgtest
{
  [DependsOn(typeof(AbpNHibernateModule))]
  public class NhHibernateModel:AbpModule
  {
    //重寫PreInitialize方法
    public override void PreInitialize()
    {
      var pgStr = "Server=localhost;Port=5432;Database=DTDB;User Id=DT;Password=DT";

      var config = Configuration.Modules.AbpNHibernate().FluentConfiguration
        .Database(PostgreSQLConfiguration.Standard.ConnectionString(pgStr));
      config.Mappings(a => a.FluentMappings.AddFromAssembly(Assembly.GetEntryAssembly()));
      //base.PreInitialize();
    }
    //重寫Initialize方法
    public override void Initialize()
    {
      IocManager.RegisterAssemblyByConvention(Assembly.GetCallingAssembly());
      // base.Initialize();
    }
  }
}

4、新建實體和實體對映

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Domain.Entities;
using Abp.NHibernate.EntityMappings;

/**
* 名稱空間: abpPgtest.testModel
* 功 能: 資料庫表實體及對映
* 類 名: testModel
* 作 者: 東騰
* 時 間: 2018/1/29 17:21:19 
*/
namespace abpPgtest.testModel
{
  public class testModelMap : EntityMap<testModel>
  {
    public testModelMap():base("dt_tb_test")
    {
      //Id(x => x.Id).GeneratedBy.Increment();//資料庫表中沒有自增的Id時需要對映一個Id
      Map(x => x.Company);
      Map(x => x.Name);

      //References<userModel>(a => a.Id).Not.LazyLoad().Column("外來鍵ID");//資料庫中有關聯表時使用

    }
  }
  public class testModel:Entity<int>
  {
    public virtual int Id { get; set; }

    public virtual string Name { get; set; }

    public virtual string Company { get; set; }
  }
}

5、資料庫中新建表 dt_tb_test

6、註冊並初始化abp連線

var bootstrapper = AbpBootstrapper.Create<NhHibernateModel>();
bootstrapper.Initialize();
var resp = bootstrapper.IocManager.Resolve<IRepository<testModel>>();

7、向資料庫中新增資料

//新增資料
  var model = new testModel
    {
     Name = "東騰",Company = "東騰科技"
    };
 resp.Insert(model);

開啟資料庫檢視結果:

8、更新資料

//更新資料
  var m = resp.Get(1);
  m.Name = "東騰1";
  resp.Update(m);

檢視結果

9、查詢資料

查詢所有的資料

var allList = resp.GetAllList();

按照條件進行查詢

10、刪除資料(可以根據多種方式進行刪除,用id或者where條件進行刪除)

//刪除資料,更具where條件刪除
  Expression<Func<testModel,bool>> where = a =>a.Id==3;
  resp.Delete(where);

id為3的一條資料被刪除

11、總結:

abp.NHibernate只是ABP中對NHIbernate的一個封裝,只要正確註冊和訪問資料庫,其餘的就是ORM操作資料庫,就簡單了。其他的關係型資料都用類似的做法即可。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。