本文来自:http://fluentdata.codeplex.com/wikipage?title=Fluency&referringTitle=Home

Documentation  Fluency

This contribution is an attempt to speedup the development of domain layer in bottom to top model with FluentData. This means you already have the Database created and you need a quick way to write the Entity wrapers and common CURD operations. The goal of fluency is to provide T4 templates to generate a domain layer which has very minimal learning curve and very simple to use. At the moment Fluency supports the Table Data Gateway pattern which is very simple to understand and use.

How to use Fluency Templates?

The recommended way to use Fluency Template is by using TextTransform.exe tool. This is a command-line tool that you can use to transform a text template. When you call TextTransform.exe, you specify the name of a text template file as an argument. TextTransform.exe calls the text transformation engine and processes the text template. This tool accepts optional parameters in case your template requires some parameters which is the case with the template you will be using. TextTransform.exe is located in the following directory:

\Program Files\Common Files\Microsoft Shared\TextTemplating\10.0 
or
\Program Files\Common Files\Microsoft Shared\TextTemplating\11.0 

depending upon which version of visual studio you have. Also depending upon if you are using 64bit OS you may need to look under Program Files(X86) for the above location.

Adding new external tool

First of all you need to locate the TextTransform.exe as explained above. For my install since I am using Visual Studio 2010(32bit) on 64bit windows the location of TextTransform.exe is following
C:\Program Files (x86)\Common Files\Microsoft Shared\TextTemplating\10.0\TextTransform.exe

Now we have to do the following steps in order to add a new external tool under Visual Studio Tools menu.

  1. Copy Fluency folder from Contributions and move it under your Solution folder.
  2. Open Visual Studio and go to Tools -> External Tools menu and click Add button. This will add a blank external tool.
  3. In Title textbox enter Fluency while in Command textbox enter the full path to TextTransform.exe which in my case is C:\Program Files (x86)\Common Files\Microsoft Shared\TextTemplating\10.0\TextTransform.exe
  4. Now place following text in Arguments textbox
$(SolutionDir)\Fluency\TableDataGateway.tt -out  $(SolutionDir)/Entities.Generated.cs -a !!ns!MyDomain -a !!cs!Server=YOUR_SERVER_NAME;Database=MyDb;Trusted_Connection=true -a !!csn!MyDb
  • Here $(SolutionDir)\Fluency\TableDataGateway.tt is the path to template under your solution folder.
  • -out $(SolutionDir)/Entities.Generated.cs tells the path and name of generated file in your solution folder.
  • -a !!ns!MyDomain tells the template about namespace for generated code where !!ns is parameter name and !MyDomain tells value which is MyDomain.
  • -a !!cs!Server=YOUR_SERVER_NAME;Database=MyDb;Trusted_Connection=true tells the database connection string from where template has to generate the code.
  • Lastly -a !!csn!MyDb tells the name of connection string in web.config which will be used by generated code when opening a database connection. In this case connection string name is MyDb you will replace this with what ever is yours.

Now click OK button and new external tool will be added to your Tools menu. Finally open your Solution in Visual Studio and then go to Tools menu and click on Fluency. It will open a dialogue box just click on OK button and it will generate the code under you solutoin folder! Now that template is configured you can always regenerate your code in few clicks.

Understanding the generated code !!

There will be two classes generated for every table in database. First one will be entity class which will contain fields corrosponding to Database table. The second will be Gateway class which will contain common method for CURD operations. Lets suppose we have a table called Product in Database with following schema

        CREATE TABLE [dbo].[Product](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](256) NOT NULL,
[Price] [decimal](18, 2) NOT NULL,
[Sku] [nvarchar](256) NULL,
[Description] [nvarchar](max) NULL,
[ManufacturerId] [int] NULL,
[CreatedOn] [datetime] NULL,
[ModifiedOn] [datetime] NULL
CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED ([Id] ASC))

The code generated for product table will consist of following two classes

        /// <summary>
/// Product entity class
/// </summary>
public partial class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Sku { get; set; }
public string Description { get; set; }
public int ManufacturerId { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime ModifiedOn { get; set; }
} /// <summary>
/// Product gateway class
/// </summary>
public partial class ProductGateway
{
private static IDbContext Context()
{
return new DbContext().ConnectionStringName("MyDb",
new SqlServerProvider());
} public static Product Select(int id)
{
using(var context = Context())
{
return context.Sql(" SELECT * FROM Product WHERE Id = @id ")
.Parameter("id", id)
.QuerySingle<Product>();
}
} public static List<Product> SelectAll()
{
return SelectAll(string.Empty);
} public static List<Product> SelectAll(string sortExpression)
{
return SelectAll(0, 0, sortExpression);
} public static List<Product> SelectAll(int startRowIndex, int maximumRows, string sortExpression)
{
using (var context = Context())
{
var select = context.Select<Product>(" * ")
.From(" Product "); if (maximumRows > 0)
{
if (startRowIndex == 0)
startRowIndex = 1; select.Paging(startRowIndex, maximumRows);
} if (!string.IsNullOrEmpty(sortExpression))
select.OrderBy(sortExpression); return select.QueryMany();
}
} public static int CountAll()
{
using (var context = Context())
{
return context.Sql(" SELECT COUNT(*) FROM Product ")
.QuerySingle<int>();
}
} public static List<Product> SelectByManufacturer(int manufacturerId)
{
return SelectByManufacturer(manufacturerId, string.Empty);
} public static List<Product> SelectByManufacturer(int manufacturerId, string sortExpression)
{
return SelectByManufacturer(manufacturerId, 0, 0, sortExpression);
} public static List<Product> SelectByManufacturer(int manufacturerId, int startRowIndex, int maximumRows, string sortExpression)
{
using (var context = Context())
{
var select = context.Select<Product>(" * ")
.From(" Product ")
.Where(" ManufacturerId = @manufacturerid ")
.Parameter("manufacturerid", manufacturerId); if (maximumRows > 0)
{
if (startRowIndex == 0)
startRowIndex = 1; select.Paging(startRowIndex, maximumRows);
} if (!string.IsNullOrEmpty(sortExpression))
select.OrderBy(sortExpression); return select.QueryMany();
}
} public static int CountByManufacturer(int manufacturerId)
{
using (var context = Context())
{
return context.Sql(" SELECT COUNT(*) FROM Product WHERE ManufacturerId = @manufacturerid")
.Parameter("manufacturerid", manufacturerId)
.QuerySingle<int>();
}
} public static bool Insert(Product product)
{
using (var context = Context())
{
int id = context.Insert<Product>("Product", product)
.AutoMap(x => x.Id)
.ExecuteReturnLastId<int>(); product.Id = id;
return id > 0;
}
}
public static bool Update(Product product)
{
using (var context = Context())
{
return context.Update<Product>("Product", product)
.AutoMap(x => x.Id)
.Execute() > 0;
}
} public static bool Delete(Product product)
{
return Delete(product.Id);
} public static bool Delete(int id)
{
using (var context = Context())
{
return context.Sql(" DELETE FROM Product WHERE Id = @id ")
.Parameter("id", id)
.Execute() > 0;
}
}
}

Select single product by Id

        Product product = ProductGateway.Select(103);

Select all products

        List<Product> products = ProductGateway.SelectAll();

Count all products

        int count = ProductGateway.CountAll();

Select all products with paging

        // LOAD FIRST 20 PRODUCTS ORDER BY ID
List<Product> products = ProductGateway.SelectAll(1, 20, "Id ASC");

Select all products for manufacturer foreign key

        // LOAD FIRST 20 PRODUCTS ORDER BY NAME FOR MANUFACTURER ID 91
List<Product> products = ProductGateway.SelectByManufacturer(91,1, 20, "Name ASC");

Insert new product

            Product product = new Product() { Name = "New Product", Price = 111, Sku = "SKU-111", Description = "None" };
ProductGateway.Insert(product); // IF PRIMARYKEY IS IDENTITY THEN IT WILL BE SET BACK TO THE OBJECT
Console.Writeline(string.Format("Product Id = {0}", product.Id));

Update existing product

        Product product = ProductGateway.Select(103);
product.Price = 200;
ProductGateway.Update(product);

Delete existing product

        Product product = ProductGateway.Select(103);
ProductGateway.Delete(product);
 

Last edited Jun 25, 2013 at 6:55 AM by leadfoot, version 28

[转]FluentData的更多相关文章

  1. FluentData(微型ORM)

    using FluentData; using System; using System.Collections.Generic; using System.Linq; using System.Te ...

  2. 在不安装mysql-connector-net的情况下使用FluentData框架

    最近在开发项目中使用了FluentData框架,通过使用这个框架减少了很多开发的工作量,FluentData是一个轻量级的框架操作起来的自由度很大也少了很多负责的配置.但是在开发的时候发现一个问题就是 ...

  3. 微型orm fluentdata

    http://fluentdata.codeplex.com/documentation#Query

  4. FluentData Mysql分页的一个BUG

    开发环境 FluentData3.0.VS.NET2010.Mysql5.0 问题描述 使用FluentData对一个表(记录数28)进行分页时,突然发现一个诡异的问题,第一页返回10条数据正常,第二 ...

  5. FluentData,它是一个轻量级框架,关注性能和易用性。

    http://www.cnblogs.com/zengxiangzhan/p/3250105.html FluentData,它是一个轻量级框架,关注性能和易用性. 下载地址:FlunenData.M ...

  6. 快速上手如何使用FluentData

    http://blog.itpub.net/29511780/viewspace-1194048/ 目录:  一.什么是ORM? 二.使用ORM的优势 三.使用ORM的缺点 四.NET下的ORM框架有 ...

  7. FluentData官方文档翻译

    开始 要求 .NET 4.0. 支持的数据库 MS SQL Server using the native .NET driver. MS SQL Azure using the native .NE ...

  8. FluentData微型ORM

    最近在帮朋友做一个简单管理系统,因为笔者够懒,但是使用过的NHibernate用来做这中项目又太不实际了,索性百度了微型ORM,FluentData是第一个跳入我眼睛的词.简单的了解下FluentDa ...

  9. Oracle+FluentData+MVC4+EasyUI开发权限管理系统之开篇

    在园子里有很多EF+MVC+EasyUI的框架实在是太多了,经过在一段时间的学习高手写的思路,但是都是针对Sql数据的,但是今年我当上研发组组长的第一个任务就是编写一个通用平台框架,一刚开始想把学习过 ...

  10. orm fluentdata使用相关文章

    微型orm fluentdata使用:http://www.360doc.com/content/12/1228/23/9200790_256885743.shtml

随机推荐

  1. [WCF安全2]使用wsHttpBinding构建UserName授权的WCF应用程序,非SSL

    上一篇文章中介绍了如何使用basicHttpBinding构建UserName授权的WCF应用程序,本文将为您介绍如何使用wsHttpBinding构建非SSL的UserName安全授权的WCF应用程 ...

  2. Iterator(迭代器)

    意图: 提供一种方法顺序访问一个聚合对象中各个元素, 而又不需暴露该对象的内部表示. 适用性: 访问一个聚合对象的内容而无需暴露它的内部表示. 支持对聚合对象的多种遍历. 为遍历不同的聚合结构提供一个 ...

  3. QWebEngine_C++_交互

    参考网址:http://blog.csdn.net/liuyez123/article/details/50509788 ZC: 该文章里面的: “ <ahref="javascrip ...

  4. Vue.js的类Class 与属性 Style如何绑定

    Vue.js的类Class 与属性 Style如何绑定 一.总结 一句话总结:数据绑定一个常见需求是操作元素的 class 列表和它的内联样式.因为它们都是属性,我们可以用 v-bind 处理它们:我 ...

  5. Rails-Treasure chest3 嵌套表单; Ransack(3900✨)用于模糊查询, ranked-model(800🌟)自订列表顺序; PaperTrail(5000✨)跟踪model's data,auditing and versioning.

    自订列表顺序, gem 'ranked-model' 多步骤表单 显示资料验证错误讯息 资料筛选和搜寻, gem 'ransack' (3900✨); 软删除和版本控制 数据汇出(csv), 自订列表 ...

  6. 网络安全:攻击和防御练习(全战课), DDos压力测试

    XSS 跨站脚本攻击: Cross-site scripting(简称xss)跨站脚本. 一种网站的安全漏洞的攻击,代码注入攻击的一种.XSS攻击通常指的是通过利用网页开发时留下的漏洞,通过巧妙的方法 ...

  7. angularJs---route

    route route---‘路由’ ajax的弊端: 1.ajax请求不会留下history记录 2.用户无法直接通过url进入应用中的指定页面(保存书签,分享朋友?) 3.ajax不利于SEO 前 ...

  8. rabbitmq 对多服务器p2p模式配置的一个测试

    一直对rabbitmq p2p 模式的多服务器下做相同配置的 各个服务器数据接受情况比较好奇 今天有空测试了下 xml 文件 <?xml version="1.0" enco ...

  9. IIS网页GZIP压缩

    1.开GZIP有什么好处? 答:Gzip开启以后会将输出到用户浏览器的数据进行压缩的处理,这样就会减小通过网络传输的数据量,提高浏览的速度. 2.如何启用IIS的Gzip压缩功能: 答:首先,如果你需 ...

  10. openfalcon源码分析之hbs

    openfalcon源码分析之hbs 本节内容 hbs功能 hbs源码分析 hbs设计优劣 1. hbs功能 hbs在整个open-falcon项目中承担的角色就是连接数据库,作为数据库缓存,缓存配置 ...