ServiceStack.OrmLite 笔记2 -增

阻止并发下的产品超卖思路是利用redis串行处理数据,但又有高并发处理数据的能力

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语句

创建表

前一篇忘记写创建表了,这里补上。(其实前一篇也有那么一点)

建议安装源码里的t4模板看看效果先。

public 的属性才有效

在表被创建或者删除的时候执行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 {}

public class PocoTable
{
public int Id { get; set; }

[CustomField("CHAR(20)")] //这里是数据库的类型的字段的验证,和fluentvalidation 不太一样,fluentvalidation更多是对类的字段验证。 这里的 [CustomField("CHAR(20)")]是和ef差不多,是指和数据库的映射
public string CharColumn { get; set; }

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

}
db.CreateTable();
生成sql:
CREATE TABLE “PocoTable”
(
“Id” INTEGER PRIMARY KEY,
“CharColumn” CHAR(20) NULL,
“DecimalColumn” DECIMAL(18,4) NULL
);

//外键和引用 建议自己建几个表,亲手撸一下。av看再多,不如约个来一发
public class TableWithAllCascadeOptions
{
[AutoIncrement] public int Id { get; set; }

[References(typeof(ForeignKeyTable1))]
public int SimpleForeignKey { get; set; }

[ForeignKey(typeof(ForeignKeyTable2), OnDelete = "CASCADE", OnUpdate = "CASCADE")]
public int? CascadeOnUpdateOrDelete { get; set; }

[ForeignKey(typeof(ForeignKeyTable3), OnDelete = "NO ACTION")]
public int? NoActionOnCascade { get; set; }

[Default(typeof(int), "17")]  //默认值
[ForeignKey(typeof(ForeignKeyTable4), OnDelete = "SET DEFAULT")]
public int SetToDefaultValueOnDelete { get; set; }

[ForeignKey(typeof(ForeignKeyTable5), OnDelete = "SET NULL")]
public int? SetToNullOnDelete { get; set; }

}

db.DropAndCreateTable();//删除然后添加表
dbFactory.Run(db => db.CreateTable(overwrite:false));//不解释
看姿势
db.CreateTable(true);// overwrite 直给

//批量添加 用事务
db.DropAndCreateTable();
var rows = “A,B,B,C,C,C,D,D,E”.Split(‘,’).Map(x => new
LetterFrequency { Letter = x });
db.InsertAll(rows);

实现在这里
internal static void InsertAll(this IDbCommand dbCmd, IEnumerable
objs)
{
IDbTransaction dbTrans = null;

        try
        {
            if (dbCmd.Transaction == null)
                dbCmd.Transaction = dbTrans = dbCmd.Connection.BeginTransaction();

            var dialectProvider = dbCmd.GetDialectProvider();

            dialectProvider.PrepareParameterizedInsertStatement<T>(dbCmd);

            foreach (var obj in objs)
            {
                if (OrmLiteConfig.InsertFilter != null)
                    OrmLiteConfig.InsertFilter(dbCmd, obj);

                dialectProvider.SetParameterValues<T>(dbCmd, obj);

                try
                {
                    dbCmd.ExecNonQuery();
                }
                catch (Exception ex)
                {
                    Log.Error("SQL ERROR: {0}".Fmt(dbCmd.GetLastSqlAndParams()), ex);
                    throw;
                }
            }

            if (dbTrans != null)
                dbTrans.Commit();
        }
        finally
        {
            if (dbTrans != null)
                dbTrans.Dispose();
        }
    }

产品表(product) 

class Product

{

  public int Id{get;set} //自增Id

       public string Name{get;set}//产品名称

       public int Number{get;set}//库存

       public DateTime NTime{get;set;}//库存同步时间

       ….

}

库存变更记录表(productNumberRecord)

class productNumberRecord

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*
*
Website