2: where ProductId = @ProductId1 or ProductId = @ProductId2\ 3: .Parameter(\, 1) 4: .Parameter(\, 2) 5: .QueryMany
FluentData入门(四)--Mapping
映射
自动映射 – 在数据库对象和.Net object自动进行1:1匹配
1: List
2: from Product\
3: .QueryMany
自动映射到一个自定义的Collection:
1: ProductionCollection products = Context.Sql(\).QueryMany
如果数据库字段和POCO类属性名不一致,使用SQL别名语法AS:
1: List
2: c.CategoryId as Category_CategoryId,
3: c.Name as Category_Name
4: from Product p
5: inner join Category c on p.CategoryId = c.CategoryId\
6: .QueryMany
在这里p.*中的ProductId和ProductName会自动映射到Prodoct.ProductId和Product.ProductName,而
Category_CategoryId
和
Category_Name 将映射到 Product.Category.CategoryId 和
Product.Category.Name.
使用dynamic自定义映射规则
1: List
2: .QueryMany
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
2: .QueryMany
3:
4: public void Custom_mapper_using_datareader(Product product, IDataReader row)
5: {
6: product.ProductId = row.GetInt32(\);
7: product.Name = row.GetString(\);
8: }
或者,当你需要映射到一个复合类型时,可以使用QueryComplexMany或者QueryComplexSingle。
1: var products = new List
2: Context.Sql(\).QueryComplexMany
3:
4: private void MapComplexProduct(IList
5: {
6: var product = new Product();
7: product.ProductId = reader.GetInt32(\);
8: product.Name = reader.GetString(\);
9: products.Add(product);
10: }
多结果集
FluentData支持多结果集。也就是说,可以在一次数据库查询中返回多个查询结果。使用该特性的时候,记得使用类似下面的语句对查询语句进行包装。需要在查询结束后把连接关闭。
1: using (var command = Context.MultiResultSql)
2: {
3: List
4: @\
5: select * from Product;\
6:
7: List
8: }
执行第一个查询时,会从数据库取回数据,执行第二个查询的时候,FluentData可以判断出这是一个多结果集查询,所以会直接从第一个查询里获取需要的数据。 分页
1: List
2: .From(@\
3: inner join Category c on c.CategoryId = p.CategoryId\
4: .Where(\)
5: .OrderBy(\)
6: .Paging(1, 10).QueryMany();
调用 Paging(1, 10),会返回最先检索到的10个Product。
FluentData入门(五)—Insert, Update, Delete 插入数据 使用 SQL 语句:
1: int productId = Context.Sql(@\
2: values(@0, @1);\
3: .Parameters(\, 1)
4: .ExecuteReturnLastId
使用builder:
1: int productId = Context.Insert(\)
2: .Column(\, \)
3: .Column(\, 1)
4: .ExecuteReturnLastId
使用builder,并且自动映射
1: Product product = new Product();
2: product.Name = \;
3: product.CategoryId = 1;
4:
5: product.ProductId = Context.Insert
6: .AutoMap(x => x.ProductId)
7: .ExecuteReturnLastId
8:
将ProductId作为AutoMap方法的参数,是要指明ProductId不需要进行映射,因为它是一个数据库自增长字段。 更新数据 使用SQL语句:
1: int rowsAffected = Context.Sql(@\
2: where ProductId = @1\
3: .Parameters(\, 1)
4: .Execute();
使用builder:
1: int rowsAffected = Context.Update(\)
2: .Column(\, \)
3: .Where(\, 1)
4: .Execute();
使用builder,并且自动映射:
1: Product product = Context.Sql(@\
2: where ProductId = 1\