一、示例用数据库为Northwind数据库,可在百度网盘下载
https://pan.baidu.com/s/1er0Mm48kUfeAsYkSW6DfnA 密码:r7pm
二、如何初始化SqlRepoEx请参看上一篇博文《轻量ORM-SqlRepoEx (二)初始化SqlRepoEx》
三、生成示例用类
public class Customers
{
#region 业务属性定义
public string CustomerID { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
#endregion
}
四、一个简单的Select调用
var repository = RepoFactory.Create<Customers>();
var results = repository.Query()
.Select(e => e.CustomerID, e => e.ContactName, e => e.CompanyName)
.OrderBy(e => e.CustomerID)
.Top(20)
.Go();
foreach (var item in results)
{
Console.WriteLine($"{item.CustomerID}\t {item.ContactName}\t\t {item.CompanyName} ");
}
得到如下结果:
ALFKI Maria Anders Alfreds Futterkiste
ANATR Ana Trujillo Ana Trujillo Emparedados y helados
ANTON Antonio Moreno Antonio Moreno Taquería
AROUT Thomas Hardy Around the Horn
BERGS Christina Berglund Berglunds snabbk?p
BLAUS Hanna Moos Blauer See Delikatessen
BLONP Frédérique Citeaux Blondesddsl père et fils
BOLID Martín Sommer Bólido Comidas preparadas
BONAP Laurence Lebihan Bon app'
BOTTM Elizabeth Lincoln Bottom-Dollar Markets
BSBEV Victoria Ashworth B's Beverages
CACTU Patricio Simpson Cactus Comidas para llevar
CENTC Francisco Chang Centro comercial Moctezuma
CHOPS Yang Wang Chop-suey Chinese
COMMI Pedro Afonso Comércio Mineiro
CONSH Elizabeth Brown Consolidated Holdings
DRACD Sven Ottlieb Drachenblut Delikatessen
DUMON Janine Labrune Du monde entier
EASTC Ann Devon Eastern Connection
ERNSH Roland Mendel Ernst Handel
如果需要打印当前查询的SQL语句,而不是运行只需要调用Sql():
var results2 = repository.Query()
.Select(e => e.CustomerID, e => e.ContactName, e => e.CompanyName)
.OrderBy(e => e.CustomerID)
.Top(20)
.Sql();
得到如下结果:
SELECT TOP (20) [dbo].[Customers].[CustomerID]
, [dbo].[Customers].[ContactName]
, [dbo].[Customers].[CompanyName]
FROM [dbo].[Customers]
ORDER BY [dbo].[Customers].[CustomerID] ASC;
四、Select
1、实例一个查询实例的Repository
2、调用Repository 的Query() 获取一个查询类SelectStatement实例,此类实现大多数SQL查询场景;
3、SelectStatement有两个重要的方法
(1)、Sql()方法,此方法会返回当前repository.Query()的实际SQL语句;
(2)、Go()方法,此方法可将当前Select返回一个IEnumerable<TEntity>结果,另外,SelectStatement还实现了 ListEntityGo<TLEntity>()方法,返回一个List<TEntity>;
4、repository.Query()可简单的调用 repository.Query().Go(),这样会返回完整的实例集;其效果与repository.Query().SelectAll().Go();是一样的,但SelectAll()可以指定当前查询别名。、;
5、如果只需要返回数据集的部分字段数据,可以采用Select(e => e.CustomerID, e => e.ContactName, e => e.CompanyName)的表达示来获取特定列的数据;