建立表
前一篇忘記寫建立表了,這裡補上。(其實前一篇也有那麼一點)
建議安裝源碼裡的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
[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();
}
}
作者:
過錯出處:http://www.cnblogs.com/wang2650/
關于作者:net開發做的久而已。十餘年時光虛度!
本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接。如有問題,可以郵件:[email protected]
聯系我,非常感謝。