前一篇忘记写创建表了,这里补上。(其实前一篇也有那么一点)
建议安装源码里的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();
}
}