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 ...
随机推荐
- ubuntu下 apt-get install 下载的文件存放的目录
apt-get把下载的deb包全部放在/var/cache/apt/archives下面,该目录下的文件可以删除.当然用 sudo apt-get clean 命令也可以,这个命令只会删除缓存起来的d ...
- 理解javascript的caller,callee,call,apply概念
在提到上述的概念之前,首先想说说javascript中函数的隐含参数:arguments Arguments 该对象代表正在执行的函数和调用它的函数的参数. [function.]arguments[ ...
- [Papers]NSE, $u$, Lorentz space [Bosia-Pata-Robinson, JMFM, 2014]
$$\bex \bbu\in L^p(0,T;L^{q,\infty}),\quad \frac{2}{p}+\frac{3}{q}=1,\quad 3<q\leq\infty. \eex$$ ...
- android操作SQLite
一.SQLite SQLite是一种转为嵌入式设备设计的轻型数据库,其只有五种数据类型,分别是: NULL: 空值 INTEGER: 整数 REAL: 浮点数 TEXT: 字符串 BLOB: 大数据 ...
- 把php.exe加入系统环境变量-使用命令行可快速执行PHP命令
有时候在执行长时间运行的脚本程序的时候,浏览器是架不住的.我们就可以使用CMD命令行或者LINUX命令行执行PHP程序 1.把PHP.EXE加入到环境变量,不用每次都进入到PHP的目录 ① 右击我的 ...
- 代码所见所得方式发布.xml
pre{ line-height:1; color:#b836b3; background-color:#000000; font-size:16px;}.sysFunc{color:#19ef0b; ...
- oracle 查看表的相关信息
1.查看当前用户的表 SELECT * FROM user_tables; 2.查看指定用户的表 SELECT * FROM all_tables WHERE owner = 'SYS';
- asp.net mvc源码分析-Action篇 IModelBinder
我们首先还是看看ReflectedParameterBindingInfo的Binder属性吧: public override IModelBinder Binder { ge ...
- MFC类目录及头文件(转)
类 描述 头文件 CAnimateCtrl 自动化通用控件 afxcmn.h CArchive afx.h CArchiveException afx.h CArray afxtempl.h CAsy ...
- 移动开发必备!15款jQuery Mobile插件
移动互联网的发展,来自PC端的网页并不能完全自适应移动端页面需求,使得响应式设计体验产生并成为潮流,也正是这样一种需求,促成了jQuery Mobile的流行.jQuery Mobile这样一款基于j ...