https://blog.csdn.net/tai532439904/article/details/77879767

环境要求

  • .NET 4.0.

支持数据库

安装

使用NuGet

  • 搜索FluentData并安装。

不使用NuGet

  1. 下载zip文件。
  2. 解压文件,并将文件复制到您的解决方案或项目文件夹中。
  3. 项目中添加对fluentdata.dll引用。

核心概念

DbContext

这是fluentdata的核心类。可以通过配置ConnectionString来定义这个类,如何连接数据库和具体数据库信息

DbCommand

这是负责对数据库执行实际查询的类。

Events

DbContext类有以下的Events(事件)支持:

  • OnConnectionClosed
  • OnConnectionOpened
  • OnConnectionOpening
  • OnErrorOnExecuted
  • OnExecuting

通过使用其中任何一个,可以在事件中,记录每个SQL查询错误或者SQL查询执行的时间等信息。

Builders

Builders(生成器)提供了一个非常好的API,用于生成SQL,用于插入、更新和删除查询。 
Builder用来创建Insert, Update, Delete等相关的DbCommand实例。

Mapping

FluentData可以将SQL查询结果自动映射成一个POCO(POCO - Plain Old CLR Object)实体类,也可以转换成一个dynamic(new in .NET 4)类型:

自动映射为实体类:

  1. 如果字段名称不包含下划线(“_”)将自动映射到具有相同名称的属性上。例如,一个名为“Name”的字段将被自动映射到名也为“Name”的属性上。
  2. 如果字段名包含下划线(“_”),将自动映射到嵌套属性上。例如,例如,一个名为“Category_Name”的字段值将自动映射到名为“Category.Name”的属性上。

如果数据库中的字段和实体类型之间存在不匹配,则可以使用SQL中的别名关键字,也可以创建自己的映射方法。检查下面的映射部分以获取代码示例。

自动映射为dynamic(动态类型)

  1. 动态类型的每一个字段都将被自动映射成具有有相同的名称的属性。例如,字段名为Name会被自动映射成名为Name的属性。

什么时候需要释放资源?

  • DbContext 需要主动释放当你在启用UseTransaction或者UseSharedConnection
  • DbContext 需要主动释放当你在启用UseMultiResult (or MultiResultSql)
  • StoredProcedureBuilder 需要主动释放当你在启用UseMultiResult

在所有其他情况下处置将由fluentdata自动处理。这意味着在执行完查询并关闭之前,数据库连接一直是打开状态。

代码实例

创建和初始化一个DbContext

可以在*.config文件中配置connection string,将connection string name或者将整个connection string作为参数传递给DbContext来创建DbContext。

重要的配置

IgnoreIfAutoMapFails – IDbContext.IgnoreIfAutoMapFails返回一个IDbContext,该实例中,如果在字段不能与属性正确映射时是否抛出异常

创建和初始化一个DbContext

通过*.config中配置的ConnectionStringName:MyDatabase创建一个DbContext

public IDbContext Context()
{
return new DbContext().ConnectionStringName("MyDatabase",
new SqlServerProvider());
} // *.config文件中内容
<connectionStrings>
<add name="MyDatabase" connectionString="server=MyServerAddress;uid=uid;pwd=pwd;database=MyDatabase;" />
</connectionStrings>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

调用DbContext的ConnectionString方法显示设置connection string来创建

//
public IDbContext Context()
{
return new DbContext().ConnectionString(
"Server=MyServerAddress;Database=MyDatabase;Trusted_Connection=True;", new SqlServerProvider());
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

其他可以使用的提供器

如果你想连接其他的非SqlServer的数据库,这是非常简单的,只需要替换上面代码中的“new SqlServerProvider()”为下面的数据提供器,比如 :AccessProviderDB2ProviderOracleProviderMySqlProviderPostgreSqlProviderSqliteProviderSqlServerCompactSqlAzureProviderSqlServerProvider

查询一组数据(Query for a list of items)

返回一组dynamic对象

List<dynamic> products = Context.Sql("select * from Product").QueryMany<dynamic>();
  • 1

返回一组强类型对象

List<Product> products = Context.Sql("select * from Product").QueryMany<Product>();
  • 1

返回一组自定义的Collection

ProductionCollection products = Context.Sql("select * from Product").QueryMany<Product, ProductionCollection>();
  • 1

返回DataTable类型: 
查看下方查询单个对象(Query for a single item)

查询单个对象(Query for a single item)

返回一个dynamic对象

dynamic product = Context.Sql(@"select * from Product
where ProductId = 1").QuerySingle<dynamic>();
  • 1
  • 2

返回一个强类型对象

Product product = Context.Sql(@"select * from Product
where ProductId = 1").QuerySingle<Product>();
  • 1
  • 2

返回一个DataTable

/**
* 其实QueryMany<DataTable>和QuerySingle<DataTable>都可以用来返回DataTable,
* 但考虑到QueryMany<DataTable>返回的是List<DataTable>,
* 所以使用QuerySingle<DataTable>来返回DataTable更方便。
*/
DataTable products = Context.Sql("select * from Product").QuerySingle<DataTable>();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

查询一个标量值

int numberOfProducts = Context.Sql(@"select count(*)
from Product").QuerySingle<int>();
  • 1
  • 2

查询一组标量值

List<int> productIds = Context.Sql(@"select ProductId
from Product").QueryMany<int>();
  • 1
  • 2

查询参数

索引形式参数:

dynamic products = Context.Sql(@"select * from Product
where ProductId = @0 or ProductId = @1", 1, 2).QueryMany<dynamic>();
  • 1
  • 2

或者:

dynamic products = Context.Sql(@"select * from Product
where ProductId = @0 or ProductId = @1")
.Parameters(1, 2).QueryMany<dynamic>();
  • 1
  • 2
  • 3

命名形式参数:

dynamic products = Context.Sql(@"select * from Product
where ProductId = @ProductId1 or ProductId = @ProductId2")
.Parameter("ProductId1", 1)
.Parameter("ProductId2", 2)
.QueryMany<dynamic>();
  • 1
  • 2
  • 3
  • 4
  • 5

OutPut形式参数:

var command = Context.Sql(@"select @ProductName = Name from Product
where ProductId=1")
.ParameterOut("ProductName", DataTypes.String, 100);
command.Execute(); string productName = command.ParameterValue<string>("ProductName");
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

List形式参数-in查询:

List<int> ids = new List<int>() { 1, 2, 3, 4 };
// 注意这里,不要在"in(...)"周围有任何空格的操作符.
dynamic products = Context.Sql(@"select * from Product
where ProductId in(@0)", ids).QueryMany<dynamic>();
  • 1
  • 2
  • 3
  • 4

like查询:

string cens = "%abc%";
Context.Sql("select * from Product where ProductName like @0",cens);
  • 1
  • 2

映射

自动映射-数据库对象与.Net对象自动进行1:1匹配:

List<Product> products = Context.Sql(@"select *
from Product")
.QueryMany<Product>();
  • 1
  • 2
  • 3

自动映射到一个自定义的Collection

ProductionCollection products = Context.Sql("select * from Product").QueryMany<Product, ProductionCollection>();
  • 1

如果数据库字段和.Net对象类属性名不一致,使用SQL别名语法AS:

/*
* 在这里p.*中的ProductId和ProductName会自动映射到Prodoct.ProductId和Product.ProductName,
* 而Category_CategoryId和Category_Name将映射到Product.Category.CategoryId和 Product.Category.Name
*/
List<Product> products = Context.Sql(@"select p.*,
c.CategoryId as Category_CategoryId,
c.Name as Category_Name
from Product p
inner join Category c on p.CategoryId = c.CategoryId")
.QueryMany<Product>();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

使用dynamic自定义映射规则:

List<Product> products = Context.Sql(@"select * from Product")
.QueryMany<Product>(Custom_mapper_using_dynamic); public void Custom_mapper_using_dynamic(Product product, dynamic row)
{
product.ProductId = row.ProductId;
product.Name = row.Name;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

使用datareader进行自定义映射:

List<Product> products = Context.Sql(@"select * from Product")
.QueryMany<Product>(Custom_mapper_using_datareader); public void Custom_mapper_using_datareader(Product product, IDataReader row)
{
product.ProductId = row.GetInt32("ProductId");
product.Name = row.GetString("Name");
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

或者当你需要映射到一个复合类型时,可以使用QueryComplexMany或者QueryComplexSingle

var products = new List<Product>();
Context.Sql("select * from Product").QueryComplexMany<Product>(products, MapComplexProduct); private void MapComplexProduct(IList<Product> products, IDataReader reader)
{
var product = new Product();
product.ProductId = reader.GetInt32("ProductId");
product.Name = reader.GetString("Name");
products.Add(product);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

多结果集

FluentData支持多结果集。也就是说,可以在一次数据库查询中返回多个查询结果。使用该特性的时候,记得使用类似下面的语句对查询语句进行包装。需要在查询结束后把连接关闭。

/**
* 执行第一个查询时,会从数据库取回数据。
* 执行第二个查询的时候,FluentData可以判断出这是一个多结果集查询,所以会直接从第一个查询里获取需要的数据。
*/
using (var command = Context.MultiResultSql)
{
List<Category> categories = command.Sql(
@"select * from Category;
select * from Product;").QueryMany<Category>(); List<Product> products = command.QueryMany<Product>();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

选择数据和分页

选择一个 builder使得选择数据和分页更简单:

// 通过调用Paging(1, 10),将返回前10个产品。
List<Product> products = Context.Select<Product>("p.*, c.Name as Category_Name")
.From(@"Product p
inner join Category c on c.CategoryId = p.CategoryId")
.Where("p.ProductId > 0 and p.Name is not null")
.OrderBy("p.Name")
.Paging(1, 10).QueryMany();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

插入数据

使用SQL

int productId = Context.Sql(@"insert into Product(Name, CategoryId)
values(@0, @1);")
.Parameters("The Warren Buffet Way", 1)
.ExecuteReturnLastId<int>();
  • 1
  • 2
  • 3
  • 4

使用builder

int productId = Context.Insert("Product")
.Column("Name", "The Warren Buffet Way")
.Column("CategoryId", 1)
.ExecuteReturnLastId<int>();
  • 1
  • 2
  • 3
  • 4

使用builder,并且自动映射:

Product product = new Product();
product.Name = "The Warren Buffet Way";
product.CategoryId = 1; // 将ProductId作为AutoMap方法的参数,是要指明ProductId不需要进行映射,因为它是一个数据库自增长字段
product.ProductId = Context.Insert<Product>("Product", product)
.AutoMap(x => x.ProductId)
.ExecuteReturnLastId<int>();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

更新数据

使用SQL

int rowsAffected = Context.Sql(@"update Product set Name = @0
where ProductId = @1")
.Parameters("The Warren Buffet Way", 1)
.Execute();
  • 1
  • 2
  • 3
  • 4

使用builder

int rowsAffected = Context.Update("Product")
.Column("Name", "The Warren Buffet Way")
.Where("ProductId", 1)
.Execute();
  • 1
  • 2
  • 3
  • 4

使用builder,并且自动映射:

Product product = Context.Sql(@"select * from Product
where ProductId = 1")
.QuerySingle<Product>();
product.Name = "The Warren Buffet Way"; // 将ProductId作为AutoMap方法的参数,是要指明ProductId不需要进行映射,因为它不需要被更新。
int rowsAffected = Context.Update<Product>("Product", product)
.AutoMap(x => x.ProductId)
.Where(x => x.ProductId)
.Execute();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

设置映射失败异常是否抛出(IgnoreIfAutoMapFails)

当从数据库中读取,如果某些数据列不映出实体类,默认情况下,将抛出异常。 
如果你想忽略异常,或者属性不需要和数据库对象进行映射,你可以设置IgnoreIfAutoMapFails(true),即可以在映射错误时不抛出异常

context.IgnoreIfAutoMapFails(true);
  • 1

插入和更新 - 常用填充方式

var product = new Product();
product.Name = "The Warren Buffet Way";
product.CategoryId = 1; var insertBuilder = Context.Insert<Product>("Product", product).Fill(FillBuilder); var updateBuilder = Context.Update<Product>("Product", product).Fill(FillBuilder); public void FillBuilder(IInsertUpdateBuilder<Product> builder)
{
builder.Column(x => x.Name);
builder.Column(x => x.CategoryId);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

删除数据

使用SQL

int rowsAffected = Context.Sql(@"delete from Product
where ProductId = 1")
.Execute();
  • 1
  • 2
  • 3

使用builder

int rowsAffected = Context.Delete("Product")
.Where("ProductId", 1)
.Execute();
  • 1
  • 2
  • 3

存储过程

使用SQL

int rowsAffected = Context.Sql(@"delete from Product
where ProductId = 1")
.Execute();
  • 1
  • 2
  • 3

使用builder

var rowsAffected = Context.StoredProcedure("ProductUpdate")
.Parameter("Name", "The Warren Buffet Way")
.Parameter("ProductId", 1).Execute();
  • 1
  • 2
  • 3

使用builder,并且自动映射:

var product = Context.Sql("select * from Product where ProductId = 1")
.QuerySingle<Product>(); product.Name = "The Warren Buffet Way"; var rowsAffected = Context.StoredProcedure<Product>("ProductUpdate", product)
.AutoMap(x => x.CategoryId).Execute();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

使用builder,并且自动映射和表达式:

var product = Context.Sql("select * from Product where ProductId = 1")
.QuerySingle<Product>();
product.Name = "The Warren Buffet Way"; var rowsAffected = Context.StoredProcedure<Product>("ProductUpdate", product)
.Parameter(x => x.ProductId)
.Parameter(x => x.Name).Execute();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

使用事物

FluentData 支持事务。如果使用事务,最好使用using语句将代码包起来,已保证连接会被关闭。默认的,如果查询过程发生异常,如事务不会被提交,会进行回滚。

using (var context = Context.UseTransaction(true))
{
context.Sql("update Product set Name = @0 where ProductId = @1")
.Parameters("The Warren Buffet Way", 1)
.Execute(); context.Sql("update Product set Name = @0 where ProductId = @1")
.Parameters("Bill Gates Bio", 2)
.Execute(); context.Commit();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

实体工厂

实体工厂负责在自动映射的时候,生成对象实例。如果需要生成复杂的实例,可以自定义实体工厂:

List<Product> products = Context.EntityFactory(new CustomEntityFactory())
.Sql("select * from Product")
.QueryMany<Product>(); public class CustomEntityFactory : IEntityFactory
{
public virtual object Resolve(Type type)
{
return Activator.CreateInstance(type);
}
}

微型 ORM-FluentData 实例详解的更多相关文章

  1. 一对一关联查询注解@OneToOne的实例详解

    表的关联查询比较复杂,应用的场景很多,本文根据自己的经验解释@OneToOne注解中的属性在项目中的应用.本打算一篇博客把增删改查写在一起,但是在改的时候遇到了一些问题,感觉挺有意思,所以写下第二篇专 ...

  2. Django框架 之 ORM查询操作详解

    Django框架 之 ORM查询操作详解 浏览目录 一般操作 ForeignKey操作 ManyToManyField 聚合查询 分组查询 F查询和Q查询 事务 Django终端打印SQL语句 在Py ...

  3. 这个贴子的内容值得好好学习--实例详解Django的 select_related 和 prefetch_related 函数对 QuerySet 查询的优化

    感觉要DJANGO用得好,ORM必须要学好,不管理是内置的,还是第三方的ORM. 最最后还是要到SQL.....:( 这一关,慢慢练啦.. 实例详解Django的 select_related 和 p ...

  4. 我的书籍《深入解析Java编译器:源码剖析与实例详解》就要出版了

    一个十足的技术迷,2013年毕业,做过ERP.游戏.计算广告,在大公司呆过,但终究不满足仅对技术的应用,在2018年末离开了公司,全职写了一本书<深入解析Java编译器:源码剖析与实例详解> ...

  5. linux基础-磁盘阵列(RAID)实例详解

    磁盘阵列(RAID)实例详解 raid技术分类 软raid技术 硬raid技术 Raid和lvm的区别 为什么选择用raid RAID详解 RAID-0 RAID-1 RAID-5 Raid-10 R ...

  6. Cocos2d-x 3.X手游开发实例详解

    Cocos2d-x 3.X手游开发实例详解(最新最简Cocos2d-x手机游戏开发学习方法,以热门游戏2048.卡牌为例,完整再现手游的开发过程,实例丰富,代码完备,Cocos2d-x作者之一林顺和泰 ...

  7. JavaScript学习笔记-实例详解-类(二)

    实例详解-类(二)   //===给Object.prototype添加只读\不可枚举\不可配置的属性objectId(function(){ Object.defineProperty(Object ...

  8. JavaScript学习笔记-实例详解-类(一)

    实例详解-类(一): //每个javascript函数(除了bind())都自动拥有一个prototype对象// 在未添加属性或重写prototype对象之前,它只包含唯一一个不可枚举属性const ...

  9. Entity Framework实例详解

    Entity Framework Code First的默认行为是使用一系列约定将POCO类映射到表.然而,有时候,不能也不想遵循这些约定,那就需要重写它们.重写默认约定有两种方式:Data Anno ...

  10. 免费的HTML5连载来了《HTML5网页开发实例详解》连载(二)

    最近新浪.百度.腾讯.京东.大众点评.淘宝等流行的网站都加大了招聘HTML5的力度,HTML5开发人员成了抢手货,本次连载的是由大众点评前端工程师和一淘网前端工程师基情奉献的<HTML5网页开发 ...

随机推荐

  1. centos7系统管理和运维实战——运维必备的网络管理技能(1)

    运维必备的网络管理技能 一.网络管理协议: 1.简单的两个概念:    DHCP(动态主机配置协议):如果网络结构要更改,需要从新初始化网络参数,手机用动态主机配置协议可以避免这个问题.客户端可以从D ...

  2. 结巴(jieba)分词

    一.介绍: jieba: “结巴”中文分词:做最好的 Python 中文分词组件 “Jieba” (Chinese for “to stutter”) Chinese text segmentatio ...

  3. Springboot中使用Xstream进行XML与Bean 相互转换

    在现今的项目开发中,虽然数据的传输大部分都是用json格式来进行传输,但是xml毕竟也会有一些老的项目在进行使用,正常的老式方法是通过获取节点来进行一系列操作,个人感觉太过于复杂.繁琐.推荐一套简单的 ...

  4. 提示“Web打印服务CLodop未安装启动”的各种原因和解决方法

    旧版提示:"CLodop云打印服务(localhost本地)未安装启动!"新版提示:"Web打印服务CLodop未安装启动,点击这里下载执行安装(若此前已安装过,可点这里 ...

  5. 【python练习题】程序17

    #题目:输入一行字符,分别统计出其中英文字母.空格.数字和其它字符的个数. s = input('请输入字符串:') alf = 0 space = 0 digi = 0 other = 0 for ...

  6. 用“人话”解释不精确线搜索中的Armijo-Goldstein准则及Wolfe-Powell准则

    转载请注明出处:http://www.codelast.com/ line search(一维搜索,或线搜索)是最优化(Optimization)算法中的一个基础步骤/算法.它可以分为精确的一维搜索以 ...

  7. UOJ272 [清华集训2016] 石家庄的工人阶级队伍比较坚强 【分治乘法】

    题目分析: 首先不难注意到式子就是异或卷积,所以考虑用分治乘法推出优化方法.我们把一个整体$f$拆成$f-,f\pm,f+$,然后另一个拆成$g-,g\pm,g+$.这样做的好处是能更清楚的分析问题. ...

  8. BZOJ4818 [SDOI2017] 序列计数 【矩阵快速幂】

    题目分析: 一个很显然的同类项合并.注意到p的大小最大为100,考虑把模p意义下相同的求出来最后所有的减去没有质数的做矩阵快速幂即可. 代码: #include<bits/stdc++.h> ...

  9. 【CF768G】The Winds of Winter 可持久化线段树 DFS序

    题目大意 给定一棵\(n\)个点的树,对于树上每个结点,将它删去,然后可以将得到的森林中任意一个点与其父亲断开并连接到另一颗树上,对每一个点求出森林中所有树\(size\)最大值的最小值. \(n\l ...

  10. Awesome-3d

    1.素描-你的3D内容在网络,移动,AR,和虚拟现实. 2.跨平台AR SDK =======================