wangyan188 发表于 2016-11-22 08:50:06

NBearLite使用入门

  NBearLite是NBearV4的几个核心组件之一,也是目前NBearV3中ORM部分的查询语法的核心。NBearLite本身并不是一个完整的ORM解决方案,配合目前Teddy正常开发的NBearMapping组件使用(某个中间组件过渡),组成一套完整强大的ORM解决方案。NBearLite的目标是提供一种SQL语句和存储过程透明的方便快捷,面向对象化的数据库操作,专门负责SQL语句生成,数据库连接管理,事务管理,参数管理,提供各种查询接口。
  在NBearV3中希望从一个表中根据条件查询出数据对象,可以使用如下对象查询语法:


1 Product[] products = gateway.From<Product>().Where((Product._.UnitsInStock <= Product._.ReorderLevel
&& !(Product._.Discontinued == true)) || Product._.UnitPrice < 10m).ToArray<Product>;
  1 Product[] products = gateway.From<Product>().Where((Product._.UnitsInStock <= Product._.ReorderLevel && !(Product._.Discontinued == true)) || Product._.UnitPrice < 10m).ToArray<Product>;
  这里,从对象逻辑语法到SQL语句的生成,再到结果集映射,NBearV3的Gateway对象一手包办。
  ds = db.Select(Northwind.Categories, Northwind.Categories.CategoryName).Where(Northwind.Categories.CategoryID > 0).ToDataSet();
  在NBearLite中,继承保留了NBearV3的对象查询语法,专职负责查询。而且只保留了ToDataReader,ToDataSet,ToScalar等返回ADO.NET原生数据对象的接口,与实体没有直接的联系。如下代码取自,NBearLite DatabaseTest:

ds = db.Select(Northwind.Categories, Northwind.Categories.CategoryName).
Where(Northwind.Categories.CategoryID > 0).ToDataSet();
在NBearLite中,数据接口由Gateway变成了Database,所有的数据库操作都是通过Database所提供的接口来完成。在NBearLite也不需要定义和创建与数据库字段相关的实体类(不需要映射),那么如何实现对象化的数据库操作呢?在NBearLite中,提供了一个中NBearLite.QueryColumnsGenerator的代码生成工具,故名思意,就是用于生成查询字段描述代码的工具。该工具可以生成整个数据库,包括包,视图的字段描述定义,存储过程的函数式调用的包装代码。  字段描述定义,可以参看NBearV3中,实体类的@__Columns内联类的定义,实际工具生成的就是这段代码。存储过程的包装代码确实有点创意,如下:

public static System.Data.DataSet CustOrderHist(NBearLite.Database db, out int RETURN_VALUE, string CustomerID)
    {
      if ((db == null))
      {
            throw new System.ArgumentNullException("db", "Parameter: db could not be null!");
      }
      NBearLite.StoredProcedureSection spSection = db.StoredProcedure("CustOrderHist");
      System.Collections.Generic.Dictionary<string, object> outValues;
      spSection.SetReturnParameter("RETURN_VALUE", System.Data.DbType.Int32, 0);
      spSection.AddInputParameter("CustomerID", System.Data.DbType.StringFixedLength, CustomerID);
      System.Data.DataSet ds = spSection.ToDataSet(out outValues);
      RETURN_VALUE = ((int)(outValues["RETURN_VALUE"]));
      return ds;
    }
  这样我们调用该存储过程就可以直接使用函数传参和获得返回值,完全可以避免烦杂的ADO.NET对象操作,便于调用和维护。对数据库中的每个存储过程,NBearLite都会生成一个与之对应的调用函数。

  现在,参照NBearLite的Test用例,简单介绍一下NBearLite该如何使用。首先要创建一个Database对象,Database db = new Database("Northwind");该构造函数可接受多种重载,这种是最常用的重载方式,”Northwind”是在application config 中定义好的一个数据库连接串名称。



<add name="Northwind" connectionString="Server=(local);Database=Northwind;Uid=sa;Pwd=sa" />  该配置节的providerName属性名可以用于指定使用哪种NBearLite Db Provider,如下配置节就表示,客户系统希望使用postgresql数据库:

<add name="Postgres" connectionString="User ID=postgres;Password=sasa;Host=localhost;Port=5432;Database=postgres;
Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;" providerName="postgresql" />
Database对象生成后,就所有的数据库操作都是通过它来完成的,其中Northwind类就是由NBearLite.QueryColumnsGenerator生成的数据库描述类:  1. 往数据库插入一条只有一个CategoryName字段值的记录


db.Insert(Northwind.Categories).AddColumn(Northwind.Categories.CategoryName, "test1").Execute()  2. 根据条件更新字段值


db.Update(Northwind.Categories).AddColumn(Northwind.Categories.CategoryName, "test1").
Where(Northwind.Categories.CategoryName == "test1").Execute()3. 根据条件删除记录

db.Delete(Northwind.Categories).Where(Northwind.Categories.CategoryName == "test111").Execute()  4. 查询记录
a) 简单查询


DataSet ds = db.Select(Northwind.Categories).ToDataSet();  //查询Northwind数据库的Categories表中的所有记录。


ds = db.Select(Northwind.Categories, Northwind.Categories.CategoryName).
Where(Northwind.Categories.CategoryID > 0).ToDataSet();  //查询返回Categories中CategoryID大于0的CategoryName列记录。
  b) 复杂查询

db.Select(Northwind.Categories, Northwind.Categories.CategoryName).
GroupBy(Northwind.Categories.CategoryName).OrderBy(Northwind.Categories.CategoryName.Desc).
SetSelectRange(2, 2, Northwind.Categories.CategoryName).ToDataSet()
  //根据CategoryName分组,排序,并返回从第3行开始的前两条数据。

db.Select(Northwind.Categories, Northwind.Categories.__Alias("CategoriesAlias").CategoryName).
Join(Northwind.Categories, "CategoriesAlias", Northwind.Categories.CategoryID ==
Northwind.Categories.__Alias("CategoriesAlias").CategoryID).

SetSelectRange(2, 2, Northwind.Categories.CategoryID).Where(Northwind.Categories.CategoryName.Length > 0 &&
Northwind.Categories.__Alias("CategoriesAlias").Description != null).

ToDataSet();
  //上面的语句演示了如何进行表之间的关联查询
  5. 调用存储过程
  Northwind.SalesbyYear(db, out ret, new DateTime(1800, 9, 9), DateTime.Now);
  NBearLite本身并不需要任何的外部配置的支持,对象化的查询语法会自动生成SQL语句的同时,也提供了多种数据库透明的可能。目前NBearLite中已实现的Db Provider包括:SqlServer(2000/2005),Oracle,MsAccess,MySql,PostgreSql,Sqlite。大部分都是我没有使用过的。L
  最后一点,关于生成的SQL语句保存起来便于跟踪的问题。那天在MSN群里有一位朋友在问如何使用Log委托的问题,到最后愣是没让他明白。在NBear中,所有的日志记录方式都是一样的,也很简单。如下定义一个相同原型的函数(静态函数):

public static void OnLog(string sql)
    {
    }
  函数名可以不一样,参sql就是生成的SQL语句,在该函数中,我们可以决定是将该参数保存到文件中,还是显示出来。
  接下来将该函数赋值给db.OnLog属性成员
  db.OnLog += OnLog;
  += 是委托代理的使用方式。就这样,就可以实现SQL语句的跟踪了。如果对委托代理还不理解的朋友,建议可以去了解一下相关的知识。
  文中提到的相关代码和使用示例,可以到NBearLite的Test工程中得到。NBearLite的源码可以从这里下载.
  完。
  原文作者:阿不
  相关文章:
  NBearLite入门二
页: [1]
查看完整版本: NBearLite使用入门