复杂点的使用2


InsertAll, UpdateAll and DeleteAll 的参数要是IEnumerables


Each关键字 返回 IEnumerable 并且是延迟加载的


全局设置 当字符串为null时候,设置一个默认值

OrmLiteConfig.OnDbNullFilter = fieldDef = >

fieldDef.FieldType == typeof(string) ? "NULL" : null;

执行sql的时候过滤

public class MockStoredProcExecFilter : OrmLiteExecFilter

{

public override T Exec(IDbConnection dbConn, Func<IDbCommand, T> filter)

{

try

{

return base.Exec(dbConn, filter);

}

catch (Exception ex)

{

if (dbConn.GetLastSql() == "exec sp_name @firstName, @age")

return (T)(object)new Person { FirstName = "Mocked" };

throw;

}

}

}

OrmLiteConfig.ExecFilter = new MockStoredProcExecFilter();

using (var db = OpenDbConnection())

{

var person = db.SqlScalar("exec sp_name @firstName, @age",

new { firstName = "aName", age = 1 });

person.FirstName.Print(); //Mocked

}


CaptureSqlFilter

跟踪 可以在调试窗口看到了

using (var captured = new CaptureSqlFilter())

using (var db = OpenDbConnection())

{

db.Where(new { Age = 27 });

captured.SqlStatements[0].PrintDump();

}


同上 重复执行

public class ReplayOrmLiteExecFilter : OrmLiteExecFilter

{

public int ReplayTimes { get; set; }

public override T Exec<T>(IDbConnection dbConn, Func<IDbCommand, T> filter)
{
var holdProvider = OrmLiteConfig.DialectProvider;
var dbCmd = CreateCommand(dbConn);
try
{
var ret = default(T);
for (var i = 0; i < ReplayTimes; i++)
{
ret = filter(dbCmd);
}
return ret;
}
finally
{
DisposeCommand(dbCmd);
OrmLiteConfig.DialectProvider = holdProvider;
}
}

}

OrmLiteConfig.ExecFilter = new ReplayOrmLiteExecFilter { ReplayTimes = 3 };

using (var db = OpenDbConnection())

{

db.DropAndCreateTable();

db.Insert(new PocoTable { Name = "Multiplicity" });

var rowsInserted = db.Count<PocoTable>(q => q.Name == "Multiplicity"); //3

}


单元测试 模拟返回的数据

下面返回的数据都是假的,山寨的

using (new OrmLiteResultsFilter {

PrintSql = true,

SingleResult = new Person {

Id = 1, FirstName = "Mocked", LastName = "Person", Age = 100

},

})

{

db.Single(x => x.Age == 42).FirstName // Mocked

db.Single(db.From().Where(x => x.Age == 42)).FirstName // Mocked

db.Single(new { Age = 42 }).FirstName // Mocked

db.Single("Age = @age", new { age = 42 }).FirstName // Mocked

}


一看就懂 字符串过滤 还有这玩意居然

OrmLiteConfig.StringFilter = s => s.TrimEnd();

db.Insert(new Poco { Name = "Value with trailing " });

db.Select().First().Name // "Value with trailing"


可插入 可拔出的 复杂类型序列化

据说ServiceStack's的json序列化效率最高

//ServiceStack's JSON and JSV Format

SqliteDialect.Provider.StringSerializer = new JsvStringSerializer();

PostgreSqlDialect.Provider.StringSerializer = new JsonStringSerializer();

//.NET's XML and JSON DataContract serializers

SqlServerDialect.Provider.StringSerializer = new DataContractSerializer();

MySqlDialect.Provider.StringSerializer = new JsonDataContractSerializer();

//.NET XmlSerializer

OracleDialect.Provider.StringSerializer = new XmlSerializableSerializer();

code first的时候会用到吧

public class PocoTable

{

public int Id { get; set; }

[CustomField("CHAR(20)")]
public string CharColumn { get; set; } [CustomField("DECIMAL(18,4)")]
public decimal? DecimalColumn { get; set; }

}

db.CreateTable();

结果:CREATE TABLE "PocoTable"

(

"Id" INTEGER PRIMARY KEY,

"CharColumn" CHAR(20) NULL,

"DecimalColumn" DECIMAL(18,4) NULL

);


可以这样调用存储过程的

List results = db.SqlList("EXEC GetAnalyticsForWeek 1");

List results = db.SqlList(

"EXEC GetAnalyticsForWeek @weekNo", new { weekNo = 1 });

List results = db.SqlList("EXEC GetTotalsForWeek 1");

List results = db.SqlList(

"EXEC GetTotalsForWeek @weekNo", new { weekNo = 1 });

int result = db.SqlScalar("SELECT 10");

搞个带参数的存储过程

string spSql = @"DROP PROCEDURE IF EXISTS spSearchLetters;

CREATE PROCEDURE spSearchLetters (IN pLetter varchar(10), OUT pTotal int)

BEGIN

SELECT COUNT(*) FROM LetterFrequency WHERE Letter = pLetter INTO pTotal;

SELECT * FROM LetterFrequency WHERE Letter = pLetter;

END";

db.ExecuteSql(spSql);

using (var cmd = db.SqlProc("spSearchLetters", new { pLetter = "C" }))

{

var pTotal = cmd.AddParam("pTotal", direction: ParameterDirection.Output);

var results = cmd.ConvertToList<LetterFrequency>();
var total = pTotal.Value;

}

换个姿势加参数

IDbDataParameter pTotal = null;

var results = db.SqlList("spSearchLetters", cmd => {

cmd.CommandType = CommandType.StoredProcedure;

cmd.AddParam("pLetter", "C");

pTotal = cmd.AddParam("pTotal", direction: ParameterDirection.Output);

});

var total = pTotal.Value;


设置字段的默认值 g点在这里OrmLiteVariables

public class Poco

{

[Default(OrmLiteVariables.SystemUtc)] //= {SYSTEM_UTC}

public DateTime CreatedTimeUtc { get; set; }

}

ServiceStack.OrmLite 笔记8 -还是有用的姿势的更多相关文章

  1. ServiceStack.OrmLite 笔记2 -增

    ServiceStack.OrmLite 笔记2 这篇主要介绍 增加 db.Insert(new Employee { Id = 1, Name = "Employee 1" }) ...

  2. ServiceStack.OrmLite 笔记

    ServiceStack.OrmLite 笔记1 ServiceStack.OrmLite 这个东东就是个orm框架,可以实现类似ef的效果.具体的就不这里班门弄斧了. 支持 SqlServerDia ...

  3. ServiceStack.OrmLite 笔记9 -code first 必须的代码优先

    复杂点的使用3 code first的使用,支持复杂类型 public enum PhoneType { Home, Work, Mobile, } public enum AddressType { ...

  4. ServiceStack.OrmLite 笔记4 删

    删除 db.DeleteAll(); //各种姿势 db.Delete(p => p.Age == 27);// db.Delete(q => q.Where(p => p.Age ...

  5. ServiceStack.OrmLite 笔记10-group having 分页orderby等

    group having 分页等 var ev = OrmLiteConfig.DialectProvider.SqlExpression(); group的使用 同sql一样,注意group分组的字 ...

  6. ServiceStack.OrmLite 笔记5 改

    修改 db.Update(new Person { Id = 1, FirstName = "Jimi", LastName = "Hendrix", Age ...

  7. ServiceStack.OrmLite 学习笔记7-复杂点的使用1

    复杂点的使用1 先看看这2个类 class Customer { public int Id { get; set; } ... } class CustomerAddress { public in ...

  8. ServiceStack.OrmLite

    ServiceStack.OrmLite 谈谈我的入门级实体框架Loogn.OrmLite   每次看到有新的ORM的时候,我总会留意一下,因为自己也写过一个这样的框架,人总是有比较之心的.我可能会d ...

  9. ServiceStack.OrmLite中的一些"陷阱"(2)

    注:此系列不是说ServiceStack.OrmLite的多个陷阱,这仅仅个人认为是某一个陷阱(毕竟我踩坑了)而引发的思考. 前文说到了项目需要使用两种不同的数据库语言,虽说前文问题已基本解决了,但是 ...

随机推荐

  1. android 项目学习随笔十六( 广告轮播条播放)

    广告轮播条播放 if (mHandler == null) {//在此初始化mHandler , 保证消息不重复发送 mHandler = new Handler() { public void ha ...

  2. android 项目学习随笔五(JSON解析)

    1.利用Xutils获取网络数据 /** * 从服务器获取数据 需要权限: <uses-permission * android:name="android.permission.IN ...

  3. win7 chm 打开失败记录

    近期学习rails,制作的html帮助文件想生成chm文件,用了几个网上的html制作chm软件,生成的chm无法打开. 网上大部分解决方法是修改文件属性,Unlock之后可解决. 以前遇到过打不开, ...

  4. python实现指定目录下批量文件的单词计数:串行版本

    直接上代码. 练习目标: 1.  使用 Python 面向对象的方法封装逻辑和表达 : 2.  使用异常处理和日志API : 3.  使用文件目录读写API : 4.  使用 list, map, t ...

  5. xml、 Dao service 三层参数以及对应关系

    =======service   调用dao用params.put(K,Value);将参数传入后台. BaseResponse response = new BaseResponse(); Map& ...

  6. ubuntu安装最新版本的node.js

    下面的方法适用于最新版本的Ubuntu.Ubuntu 12.04 LTS.Ubuntu 12.10.Ubuntu 13.04等版本.它可以帮助开发者在Ubuntu上安装Node.js,无需从头编译安装 ...

  7. Web API 和 WCF 的比较

    现在有很多可用的技术允许你创建被不同客户端所消费的服务,这些客户端可能是Web应用程序.Windows应用程序和移动应用等.服务可以支持http协议或者其他协议.接下来的讨论仅限于ASP.NET We ...

  8. 在 VirtualBox 中 CentOS 网络设置

    转自:本文发表于水景一页.永久链接:<http://cnzhx.net/blog/minimal-centos-in-virtualbox/>.转载请保留此信息及相应链接. 4. 设置¶ ...

  9. git 上传本地文件到github

    git 上传本地文件到github 1 git config --global user.name "Your Real Name" 2 git config --global u ...

  10. 《QT Creator快速入门》

    ui中的类,这样使用无法通过调试: Ui::Dialog ui(&w); w.show(); 而需要改成: Ui::Dialog ui; ui.setupUi(&w); w.show( ...