FluentData官方文档翻译
开始
要求
- .NET 4.0.
支持的数据库
- MS SQL Server using the native .NET driver.
- MS SQL Azure using the native .NET driver.
- MS Access using the native .NET driver.
- MS SQL Server Compact 4.0 through the Microsoft SQL Server Compact 4.0 driver.
- Oracle through the ODP.NET driver.
- MySQL through the MySQL Connector .NET driver.
- SQLite through the SQLite ADO.NET Data Provider.
- PostgreSql through the Npgsql provider.
- IBM DB2
安装
如果你使用 NuGet:
- 搜索 FluentData并点击安装.
如果你没有使用 NuGet:
- 下载压缩包.
- 解压缩,将dll拷贝进你的项目.
- 项目中添加对FluentData.dll的引用.
核心思想
这个类是FluentData开始工作的入口点。它通过属性定义配置,比如数据库连接和数据库操作
Events
- OnConnectionClosed
- OnConnectionOpened
- OnConnectionOpening
- OnError
- OnExecuted
- OnExecuting
Builders
Mapping
- 如果你的字段不包含下标("_"),它就会自动映射到具有相同属性名称的属性上。比如,字段“Name”的值会自动映射到实体的“Name”属性上。
- 如果字段名称包含下标 ("_"),他就会自动映射到名称相近的属性。比如,字段“Category_Name”能够自动映射到实体的“Category.Name”属性上面。
- 对于Dyanmic类型,每一个属性名都和字段名相同。数据库查询结果会自动映射到对应名称的属性上面。
什么时候需要手动释放资源?
- 当使用UseTransaction或者UseSharedConnection时,需要手动释放DbContext。
- 如果使用UseMultiResult或者MultiResultSql时,需要手动释放DbCommand。
- 使用UseMultiResult时,需要手动释放StoredProcedureBuilder。
代码实例
DbContext类实例化时需要的数据库连接字符串,能够配置在*.config文件中,或者在代码中提供。
- IgnoreIfAutoMapFails - 在字段不能与属性正确映射时,不要抛出错误。
创建、实例化DbContext
DbContext通过调用ConnectionStringName 方法实例化,读取*.config file文件中的数据库连接:
public IDbContext Context()
{
return new DbContext().ConnectionStringName("MyDatabase",
new SqlServerProvider());
}
或者调用ConnectionStringName 方法实例化,直接提供数据库连接字符串:
public IDbContext Context()
{
return new DbContext().ConnectionString(
"Server=MyServerAddress;Database=MyDatabase;Trusted_Connection=True;", new SqlServerProvider());
}
如果你想连接其他的非SqlServer的数据库,这是非常简单的,只需要替换上面代码中的“new SqlServerProvider()”为下面的数据提供器:
AccessProvider, DB2Provider, OracleProvider, MySqlProvider, PostgreSqlProvider, SqliteProvider, SqlServerCompact, SqlAzureProvider, SqlServerProvider.
查询list集合
List<dynamic> products = Context.Sql("select * from Product").QueryMany<dynamic>();
返回一个强类型集合:
List<Product> products = Context.Sql("select * from Product").QueryMany<Product>();
返回一个用户自定义集合:
ProductionCollection products = Context.Sql("select * from Product").QueryMany<Product, ProductionCollection>();
返回DataTable:
请参考查询单条数据
查询单条数据:
返回一个Dynamic对象:
dynamic product = Context.Sql(@"select * from Product where ProductId = 1").QuerySingle<dynamic>();
返回一个强类型对象:
Product product = Context.Sql(@"select * from Product where ProductId = 1").QuerySingle<Product>();
返回一个DataTable:
DataTable products = Context.Sql("select * from Product").QuerySingle<DataTable>();
int numberOfProducts = Context.Sql(@"select count(*) from Product").QuerySingle<int>();
查询scalar数据集合
List<int> productIds = Context.Sql(@"select ProductId from Product").QueryMany<int>();
参数
索引参数:
dynamic products = Context.Sql(@"select * from Product where ProductId = @0 or ProductId = @1", 1, 2).QueryMany<dynamic>();
或者:
dynamic products = Context.Sql(@"select * from Product where ProductId = @0 or ProductId = @1")
.Parameters(1, 2).QueryMany<dynamic>();
命名参数:
dynamic products = Context.Sql(@"select * from Product where ProductId = @ProductId1 or ProductId = @ProductId2")
.Parameter("ProductId1", 1)
.Parameter("ProductId2", 2)
.QueryMany<dynamic>();
输出参数:
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");
集合参数-in查询:
List<int> ids = new List<int>() { 1, 2, 3, 4 };
//becareful here,don't leave any whitespace around in(...) syntax.
dynamic products = Context.Sql(@"select * from Product where ProductId in(@0)", ids).QueryMany<dynamic>();
like查询
string cens = "%abc%";
Context.Sql("select * from Product where ProductName like @0",cens);
映射
自动映射 - 实体和数据库表一一对应:
List<Product> products = Context.Sql(@"select * from Product")
.QueryMany<Product>();
自动映射到一个用户自定义集合:
ProductionCollection products = Context.Sql("select * from Product").QueryMany<Product, ProductionCollection>();
自动映射 - 数据库字段名和对象属性名称不一致, 使用SQL的alias关键字:
Weakly typed:
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>();
上面的代码中,p.*中的ProductId和Name字段会映射到实体的ProductId和Name属性,Category_CategoryId和Category_Name会映射到Property.Category.Id和Property.Category.Name属性上面。
使用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;
}
使用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");
}
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);
}
返回多结果集
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>();
}
在第一次被调用时,只执行一条SQL语句。第二条SQL被执行时,FluentData知道了这是一个返回多结果集的查询,就会调用上一条SQL生成的数据连接。
查询数据和分页
使用Select构建器,能够很容易的查询数据和分页:
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();
调用Paging(1, 10),前10条数据会返回
插入数据
使用 SQL:
int productId = Context.Sql(@"insert into Product(Name, CategoryId) values(@0, @1);")
.Parameters("The Warren Buffet Way", 1)
.ExecuteReturnLastId<int>();
使用构建器:
int productId = Context.Insert("Product")
.Column("Name", "The Warren Buffet Way")
.Column("CategoryId", 1)
.ExecuteReturnLastId<int>();
使用构建器及其automapping特性:
Product product = new Product();
product.Name = "The Warren Buffet Way";
product.CategoryId = 1; product.ProductId = Context.Insert<Product>("Product", product)
.AutoMap(x => x.ProductId)
.ExecuteReturnLastId<int>();
我们将ProductId传给了AutoMap方法,这样,在执行时,就不会映射ProductId的值,因为ProductId是表的主键,且是自增字段。
更新数据
使用 SQL:
int rowsAffected = Context.Sql(@"update Product set Name = @0 where ProductId = @1")
.Parameters("The Warren Buffet Way", 1)
.Execute();
使用构建器:
int rowsAffected = Context.Update("Product")
.Column("Name", "The Warren Buffet Way")
.Where("ProductId", 1)
.Execute();
使用构建器及其automapping特性:
Product product = Context.Sql(@"select * from Product where ProductId = 1")
.QuerySingle<Product>();
product.Name = "The Warren Buffet Way"; int rowsAffected = Context.Update<Product>("Product", product)
.AutoMap(x => x.ProductId)
.Where(x => x.ProductId)
.Execute();
我们将ProductId传给了AutoMap方法,这样,在执行时,就不会映射ProductId的值,因为ProductId是表的主键。
新增和更新 - 通用填充方法
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);
}
删除数据:
使用SQL:
int rowsAffected = Context.Sql(@"delete from Product where ProductId = 1")
.Execute();
使用构建器:
int rowsAffected = Context.Delete("Product")
.Where("ProductId", 1)
.Execute();
存储过程
使用SQL:
var rowsAffected = Context.Sql("ProductUpdate")
.CommandType(DbCommandTypes.StoredProcedure)
.Parameter("ProductId", 1)
.Parameter("Name", "The Warren Buffet Way")
.Execute();
使用构建器:
var rowsAffected = Context.StoredProcedure("ProductUpdate")
.Parameter("Name", "The Warren Buffet Way")
.Parameter("ProductId", 1).Execute();
使用构建器及其automapping特性:
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();
使用构建器及其automapping、expressions特性:
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();
事务
FluentData支持事务。使用事务的时候,要注意将代码包在using语句块中,释放资源。默认情况下,如果发生了异常或者没有执行Commit方法,就会回滚操作。
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();
}
实体工厂
实体工厂用于在自动映射时创建对象。如果你有一个复杂的业务模型在创建时需要做特殊处理,你能够创建你自定义的实体工厂
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);
}
} 示例代码:FluentData.7z
FluentData官方文档翻译的更多相关文章
- Flume官方文档翻译——Flume 1.7.0 User Guide (unreleased version)中一些知识点
Flume官方文档翻译--Flume 1.7.0 User Guide (unreleased version)(一) Flume官方文档翻译--Flume 1.7.0 User Guide (unr ...
- Flume官方文档翻译——Flume 1.7.0 User Guide (unreleased version)(二)
Flume官方文档翻译--Flume 1.7.0 User Guide (unreleased version)(一) Logging raw data(记录原始数据) Logging the raw ...
- 蓝牙4.0——Android BLE开发官方文档翻译
ble4.0开发整理资料_百度文库 http://wenku.baidu.com/link?url=ZYix8_obOT37JUQyFv-t9Y0Sv7SPCIfmc5QwjW-aifxA8WJ4iW ...
- GreenDao官方文档翻译(上)
笔记摘要: 上一篇博客简单介绍了SQLite和GreenDao的比较,后来说要详细介绍下GreenDao的使用,这里就贴出本人自己根据官网的文档进行翻译的文章,这里将所有的文档分成上下两部分翻译,只为 ...
- Aircrack-ng官方文档翻译[中英对照]---Airdecap-ng
Aircrack-ng官方文档翻译---Airdecap-ng Description[简介] With airdecap-ng you can decrypt WEP/WPA/WPA2 capt ...
- Aircrack-ng官方文档翻译[中英对照]---Airmon-ng
Aircrack-ng官方文档翻译---Airmon-ng Description[简介] This script can be used to enable monitor mode on wire ...
- Aircrack-ng官方文档翻译[中英对照]---Aireplay-ng
Aircrack-ng官方文档翻译---Aireplay-ng[90%] Description[简介] Aireplay-ng is used to inject frames. Aireplay- ...
- Salt Stack 官方文档翻译 - 一个想做dba的sa - 博客频道 - CSDN.NET
OSNIT_百度百科 Salt Stack 官方文档翻译 - 一个想做dba的sa - 博客频道 - CSDN.NET Salt Stack 官方文档翻译 分类: 自动运维 2013-04-02 11 ...
- Retrofit官方文档翻译
Retrofit官方文档翻译 官方文档网址 http://square.github.io/retrofit/ 介绍 Retrofit 将你的 HTTP API 转换为 Java 接口. public ...
随机推荐
- [C#搜片神器] 之P2P中DHT网络爬虫原理
继续接着上一篇写:使用C#实现DHT磁力搜索的BT种子后端管理程序+数据库设计(开源)[搜片神器] 昨天由于开源的时候没有注意运行环境,直接没有考虑下载BT种子文件时生成子文件夹,可能导致有的朋友运行 ...
- Excel导出问题(导出时不去掉前面的0)(转)
最简单的方法是:在数字前面加'符号.即代码里添加: "'" 以下均是网上搜集到的其他解答: 一.代码如下: style="mso-number-format:'/@';& ...
- 代码以兼容高亮方式发布.xml
函数名: abort 功 能: 异常终止一个进程 用 法: void abort(void); 程序例: #include <stdio.h> #include <st ...
- memset()实现及细节
memset是计算机中C/C++语言函数.将s所指向的某一块内存中的前n个 字节的内容全部设置为ch指定的ASCII值, 块的大小由第三个参数指定,这个函数通常为新申请的内存做初始化工作, 其返回值为 ...
- GRIDVIEW传值的两种方法
第一种方法:在onselectedindexchanged中写事件 第二种方法:OnRowCommand事件 前端页面: <%@ Page Language="C#" Aut ...
- O2O在线教育平台策划方案
一.情景需求痛点: 学生: 1.除了上课上课,就是作业作业,学习太枯燥不好玩怎么办?——我就是想要玩玩玩! 2.第二天要交作业,老师不在,在家作业不懂怎么办?——我想要随身老师! 3.噢耶,周末不用上 ...
- the NTP socket is in use, exiting
centos下使用如下命令手动同步服务器时间 ntpdate ntp.fudan.edu.cn 或 ntpdate ntp.api.bz 出现“the NTP socket is in use, ex ...
- leetcode@ [273] Integer to English Words (String & Math)
https://leetcode.com/problems/integer-to-english-words/ Convert a non-negative integer to its englis ...
- systemd详解
CentOS 7 使用systemd替换了SysV.Systemd目的是要取代Unix时代以来一直在使用的init系统,兼容SysV和LSB的启动脚本,而且够在进程启动过程中更有效地引导加载服务. s ...
- HD4505小Q系列故事——电梯里的爱情
Problem Description 细心的同事发现,小Q最近喜欢乘电梯上上下下,究其原因,也许只有小Q自己知道:在电梯里经常可以遇到他心中的女神HR. 电梯其实是个很暧昧的地方,只有在电梯里,小Q ...