复杂点的使用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. java使用ffmpeg和mencoder做视频格式转换

    首发:个人博客,持续更新和纠错 主要使用技术:1)FFmpeg,用于主流格式之间的转换,例如AVI,MP4,FLV等.2)MEncoder,用于奇葩格式转主流格式,例如RMVB转AVI.这样我们可以把 ...

  2. 161104、NoSQL数据库:key/value型之levelDB介绍及java实现

    简介:Leveldb是一个google实现的非常高效的kv数据库,能够支持billion级别的数据量了. 在这个数量级别下还有着非常高的性能,主要归功于它的良好的设计.特别是LSM算法.LevelDB ...

  3. SPOOL、SQLLOADER数据导出导入的一点小总结

    1.SQLLOADER的CONTROL文件 //**************************************************************************** ...

  4. oracle 日期问题

    共三部分: 第一部分:oracle sql日期比较: http://www.cnblogs.com/sopost/archive/2011/12/03/2275078.html 第二部分:Oracle ...

  5. Hibernate API申明事务边界

    在Hibernate API中,Session和Transaction接口提供了以下声明事务边界的方法: 声明事务的开始边界: Transaction tx = session.beginTransa ...

  6. org.hibernate.PropertyNotFoundException:could not find a getter for name in class ....

    Hibernate创建持久化类须符合JavaBean的规范,"get","set"后面紧跟属性的名字,并且属性名的首字母为大写.如果不遵守这个规则,Hibern ...

  7. 模拟namenode崩溃,使用secondarynamenode恢复

    方法一.使用namespaceID 1.在namenode节点上,将dfs.name.dir指定的目录中(这里是name目录)的内容情况,以此来模拟故障发生. [hadoop@node1 name]$ ...

  8. word中设置前几页为罗马数字,后几页设置为阿拉伯数字

    假如第1-5页摘要部分页脚要是罗马数字,第6页开始是正文部分是阿拉伯数字,起始页为1. WORD2003 1.将光标定位在第5页末尾处,在菜单栏中依次点击“插入——分隔符——(分节符类型)下一页”.按 ...

  9. 算法大全(c,c++)

    http://www.2cto.com/kf/201109/105758.html 算法大全(C,C++)一. 数论算法 1.求两数的最大公约数function gcd(a,b:integer):in ...

  10. IIS与ApplicationPool重启检测自动化解决方案

    IIS与ApplicationPool重启检测自动化解决方案 Friday, November 28, 2014 DA Hotfix Automatic IIS & Application P ...