FluentData官方文档翻译

来源:互联网 发布:陕西省大数据集团 录取 编辑:程序博客网 时间:2024/06/02 03:23

开始

要求

  • .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:

  1. 下载压缩包.
  2. 解压缩,将dll拷贝进你的项目.
  3. 项目中添加对FluentData.dll的引用.

核心思想

DbContext
这个类是FluentData开始工作的入口点。它通过属性定义配置,比如数据库连接和数据库操作
DbCommand
这个类负责执行数据库操作

Events

DbContext类支持下面的事件
  • OnConnectionClosed
  • OnConnectionOpened
  • OnConnectionOpening
  • OnError
  • OnExecuted
  • OnExecuting
通过这些事件,能够实现记录“错误日志”或者记录“查询开始”等功能

Builders

它是提供了一个很好的fluent API,用于生成 insert, update 和delete 的SQL语句

Mapping

FluentData 能够自动映射查询结果为dynamic类型或者你自定义的类型
自定映射为自定义类型(Entity):
  1. 如果你的字段不包含下标("_"),它就会自动映射到具有相同属性名称的属性上。比如,字段“Name”的值会自动映射到实体的“Name”属性上。
  2. 如果字段名称包含下标 ("_"),他就会自动映射到名称相近的属性。比如,字段“Category_Name”能够自动映射到实体的“Category.Name”属性上面
如果属性名称和字段名称不匹配,你可以使用SQL语法中的alias关键字或者创建你自己的映射方法。
自动映射到dynamic类型:
  1. 对于Dyanmic类型,每一个属性名都和字段名相同。数据库查询结果会自动映射到对应名称的属性上面。

什么时候需要手动释放资源?

  • 当使用UseTransaction或者UseSharedConnection时,需要手动释放DbContext。
  • 如果使用UseMultiResult或者MultiResultSql时,需要手动释放DbCommand。
  • 使用UseMultiResult时,需要手动释放StoredProcedureBuilder。
其他的时候,FluentData会自动释放资源。就是说,数据库连接会在执行SQL的时候打开并在执行完成以后自动关闭。

代码实例

初始化DbContext
DbContext类实例化时需要的数据库连接字符串,能够配置在*.config文件中,或者在代码中提供。
重要的配置
  • IgnoreIfAutoMapFails - 在字段不能与属性正确映射时,不要抛出错误。

创建、实例化DbContext
DbContext通过调用ConnectionStringName 方法实例化,读取*.config file文件中的数据库连接:

  1. public IDbContext Context()
  2. {
  3. return new DbContext().ConnectionStringName("MyDatabase",
  4. new SqlServerProvider());
  5. }

或者调用ConnectionStringName 方法实例化,直接提供数据库连接字符串:

  1. public IDbContext Context()
  2. {
  3. return new DbContext().ConnectionString(
  4. "Server=MyServerAddress;Database=MyDatabase;Trusted_Connection=True;", new SqlServerProvider());
  5. }
提供器
如果你想连接其他的非SqlServer的数据库,这是非常简单的,只需要替换上面代码中的“new SqlServerProvider()”为下面的数据提供器:
AccessProvider, DB2Provider, OracleProvider, MySqlProvider, PostgreSqlProvider, SqliteProvider, SqlServerCompact, SqlAzureProvider, SqlServerProvider.

查询list集合

返回一个Dynamic集合:
  1. List<dynamic> products = Context.Sql("select * from Product").QueryMany<dynamic>();

返回一个强类型集合:

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

返回一个用户自定义集合:

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

返回DataTable:
请参考查询单条数据

查询单条数据:

返回一个Dynamic对象:

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

返回一个强类型对象:

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

返回一个DataTable:

  1. DataTable products = Context.Sql("select * from Product").QuerySingle<DataTable>();
QueryMany<DataTable> 和 QuerySingle<DataTable>都能够返回DataTable,但是QueryMany返回的是List<DataTable>,所以建议使用QuerySingle,直接返回一个DataTable。调用QuerySingle的时候,返回的是查询结果是所有行。
查询scalar数据
  1. int numberOfProducts = Context.Sql(@"select count(*) from Product").QuerySingle<int>();

查询scalar数据集合

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

参数
索引参数:

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

或者:

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

命名参数:

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

输出参数:

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

集合参数-in查询:

  1. List<int> ids = new List<int>() { 1, 2, 3, 4 };
  2. //becareful here,don't leave any whitespace around in(...) syntax.
  3. dynamic products = Context.Sql(@"select * from Product where ProductId in(@0)", ids).QueryMany<dynamic>();

like查询

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

映射
自动映射 - 实体和数据库表一一对应:

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

自动映射到一个用户自定义集合:

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

自动映射 - 数据库字段名和对象属性名称不一致, 使用SQL的alias关键字:
Weakly typed:

  1. 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")
  2. .QueryMany<Product>();

上面的代码中,p.*中的ProductId和Name字段会映射到实体的ProductId和Name属性,Category_CategoryId和Category_Name会映射到Property.Category.Id和Property.Category.Name属性上面。

使用Dynamic自定义映射:

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

使用Datareader自定义映射:

  1. List<Product> products = Context.Sql(@"select * from Product")
  2. .QueryMany<Product>(Custom_mapper_using_datareader);
  3.  
  4. public void Custom_mapper_using_datareader(Product product, IDataReader row)
  5. {
  6. product.ProductId = row.GetInt32("ProductId");
  7. product.Name = row.GetString("Name");
  8. }
如果你有一个复合类型的对象,需要手动控制对象生成,这时可以使用QueryComplexMany/QueryComplexSingle方法:
var products = new List<Product>();
  1. Context.Sql("select * from Product").QueryComplexMany<Product>(products, MapComplexProduct);
  2.  
  3. private void MapComplexProduct(IList<Product> products, IDataReader reader)
  4. {
  5. var product = new Product();
  6. product.ProductId = reader.GetInt32("ProductId");
  7. product.Name = reader.GetString("Name");
  8. products.Add(product);
  9. }

返回多结果集
FluentData支持返回多结果集。这个特性使你在一个数据库连接中,可以执行多条数据查询语句。使用这个特性的时候,一定要注意资源的释放:

  1. using (var command = Context.MultiResultSql)
  2. {
  3. List<Category> categories = command.Sql(
  4. @"select * from Category; select * from Product;").QueryMany<Category>();
  5.  
  6. List<Product> products = command.QueryMany<Product>();
  7. }

在第一次被调用时,只执行一条SQL语句。第二条SQL被执行时,FluentData知道了这是一个返回多结果集的查询,就会调用上一条SQL生成的数据连接。

查询数据和分页
使用Select构建器,能够很容易的查询数据和分页:

  1. List<Product> products = Context.Select<Product>("p.*, c.Name as Category_Name")
  2. .From(@"Product p inner join Category c on c.CategoryId = p.CategoryId")
  3. .Where("p.ProductId > 0 and p.Name is not null")
  4. .OrderBy("p.Name")
  5. .Paging(1, 10).QueryMany();

调用Paging(1, 10),前10条数据会返回

插入数据
使用 SQL:

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

使用构建器:

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

使用构建器及其automapping特性:

  1. Product product = new Product();
  2. product.Name = "The Warren Buffet Way";
  3. product.CategoryId = 1;
  4.  
  5. product.ProductId = Context.Insert<Product>("Product", product)
  6. .AutoMap(x => x.ProductId)
  7. .ExecuteReturnLastId<int>();

我们将ProductId传给了AutoMap方法,这样,在执行时,就不会映射ProductId的值,因为ProductId是表的主键,且是自增字段。

更新数据
使用 SQL:

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

使用构建器:

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

使用构建器及其automapping特性:

  1. Product product = Context.Sql(@"select * from Product where ProductId = 1")
  2. .QuerySingle<Product>();
  3. product.Name = "The Warren Buffet Way";
  4.  
  5. int rowsAffected = Context.Update<Product>("Product", product)
  6. .AutoMap(x => x.ProductId)
  7. .Where(x => x.ProductId)
  8. .Execute();

我们将ProductId传给了AutoMap方法,这样,在执行时,就不会映射ProductId的值,因为ProductId是表的主键。

新增和更新 - 通用填充方法

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

删除数据:
使用SQL:

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

使用构建器:

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

存储过程
使用SQL:

  1. var rowsAffected = Context.Sql("ProductUpdate")
  2. .CommandType(DbCommandTypes.StoredProcedure)
  3. .Parameter("ProductId", 1)
  4. .Parameter("Name", "The Warren Buffet Way")
  5. .Execute();

使用构建器:

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

使用构建器及其automapping特性:

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

使用构建器及其automapping、expressions特性:

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

事务
FluentData支持事务。使用事务的时候,要注意将代码包在using语句块中,释放资源。默认情况下,如果发生了异常或者没有执行Commit方法,就会回滚操作。

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

实体工厂
实体工厂用于在自动映射时创建对象。如果你有一个复杂的业务模型在创建时需要做特殊处理,你能够创建你自定义的实体工厂

  1. List<Product> products = Context.EntityFactory(new CustomEntityFactory())
  2. .Sql("select * from Product")
  3. .QueryMany<Product>();
  4.  
  5. public class CustomEntityFactory : IEntityFactory
  6. {
  7. public virtual object Resolve(Type type)
  8. {
  9. return Activator.CreateInstance(type);
  10. }
  11. }
  12.  
  13. 示例代码:FluentData.7z
原创粉丝点击