ServiceStack.OrmLite 笔记2 -增

ServiceStack.OrmLite 笔记2

这篇主要介绍 增加

db.Insert(new Employee { Id = 1, Name = "Employee 1" }); //默认同步

await db.InsertAsync(new Employee { Id = 1, Name = "Employee 1" }); //异步 其他的异步类似这里的这个示例

db.InsertOnly(new Person { FirstName = "Amy" }, q => q.Insert(p => new {p.FirstName}))

// 插入部分字段 后面的参数q.Insert表示要插入的字段 生成sql: INSERT INTO "Person" ("FirstName") VALUES ('Amy')

var rowId = db.Insert(new Poco { Text = "Text" }, selectIdentity:true);// selectIdentity:true返回自增长的id

这里代码有点多 全局的插入时过滤 类似的有UpdateFilter ,感觉就是插入时对数据进行拦截,可以发挥你的想象,比如可以在这里加日志,或者扩展新的字段,做爱做的事情。

public interface IAudit

{

DateTime CreatedDate { get; set; }

DateTime ModifiedDate { get; set; }

string ModifiedBy { get; set; }

}

//表对应的类

public class AuditTableA : IAudit

{

public AuditTableA()

{

this.CreatedDate = this.ModifiedDate = DateTime.UtcNow;

}

    [AutoIncrement]
public int Id { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public string ModifiedBy { get; set; }
}

OrmLiteConfig.InsertFilter = (dbCmd, row) => {

var auditRow = row as IAudit;

if (auditRow != null)

auditRow.CreatedDate = auditRow.ModifiedDate = DateTime.UtcNow;

};

下面是上面方法的新体位,也来自官网。对数据进行验证

OrmLiteConfig.InsertFilter = OrmLiteConfig.UpdateFilter = (dbCmd, row) => {

var auditRow = row as IAudit;

if (auditRow != null && auditRow.ModifiedBy == null)

throw new ArgumentNullException("ModifiedBy");

};

try

{

db.Insert(new AuditTable());

}

catch (ArgumentNullException) {

//throws ArgumentNullException

}

db.Insert(new AuditTable { ModifiedBy = "Me!" }); //succeeds

下面的代码因为也有insert 就也放上吧

在表被创建或者删除的时候执行sql语句

[PostCreateTable("INSERT INTO TableWithSeedData (Name) VALUES ('Foo');" +

"INSERT INTO TableWithSeedData (Name) VALUES ('Bar');")]

public class TableWithSeedData

{

[AutoIncrement]

public int Id { get; set; }

public string Name { get; set; }

}

typeof(TableWithSeedData)

.AddAttributes(new PostCreateTableAttribute(

"INSERT INTO TableWithSeedData (Name) VALUES ('Foo');" +

"INSERT INTO TableWithSeedData (Name) VALUES ('Bar');"));

前戏和事后,都是可以有自己的玩法

[PreCreateTable(runSqlBeforeTableCreated)]

[PostCreateTable(runSqlAfterTableCreated)]

[PreDropTable(runSqlBeforeTableDropped)]

[PostDropTable(runSqlAfterTableDropped)]

public class Table {}

Db.ExecuteSql("INSERT INTO page_stats (ref_id, fav_count) VALUES (@refId, @favCount)", new { refId, favCount }) //直接执行sql语句

Db.ExecuteSqlAsync("UPDATE page_stats SET view_count = view_count + 1 WHERE id = @id", new { id })//直接执行sql语句

上一篇:ServiceStack.OrmLite 笔记8 -还是有用的姿势


下一篇:ServiceStack.OrmLite 笔记9 -code first 必须的代码优先