我想用自定义名称创建表,但找不到示例代码。我注意到创建表的唯一方法是通过像 db.CreateTable() 这样的泛型类型。我可以知道是否有办法动态创建表名而不是使用别名?原因是因为有时我们希望将相同的对象类型存储到不同的表中,例如 2015_january_activity、2015_february_activity。
除此之外,db.Insert 也非常受限于对象类型。无论如何要通过传入表名来插入?
我认为这些特性非常重要,因为它在 NoSQL 解决方案中存在很长时间并且非常灵活。谢谢。
OrmLite 主要是代码优先的 ORM,它使用类型化 POCO 创建和查询匹配 RDMBS 表的模式。它还支持使用自定义 SQL API 的.
使用不同表名的一种选择是在运行时更改别名,如上一个答案中所示,您可以在其中创建自定义扩展方法来修改表名,例如:
public static class GenericTableExtensions
{
static object ExecWithAlias<T>(string table, Func<object> fn)
{
var modelDef = typeof(T).GetModelMetadata();
lock (modelDef) {
var hold = modelDef.Alias;
try {
modelDef.Alias = table;
return fn();
}
finally {
modelDef.Alias = hold;
}
}
}
public static void DropAndCreateTable<T>(this IDbConnection db, string table) {
ExecWithAlias<T>(table, () => { db.DropAndCreateTable<T>(); return null; });
}
public static long Insert<T>(this IDbConnection db, string table, T obj, bool selectIdentity = false) {
return (long)ExecWithAlias<T>(table, () => db.Insert(obj, selectIdentity));
}
public static List<T> Select<T>(this IDbConnection db, string table, Func<SqlExpression<T>, SqlExpression<T>> expression) {
return (List<T>)ExecWithAlias<T>(table, () => db.Select(expression));
}
public static int Update<T>(this IDbConnection db, string table, T item, Expression<Func<T, bool>> where) {
return (int)ExecWithAlias<T>(table, () => db.Update(item, where));
}
}
Run Code Online (Sandbox Code Playgroud)
这些扩展方法提供了额外的 API,让您可以更改所使用的表的名称,例如:
var tableName = "TableA"'
db.DropAndCreateTable<GenericEntity>(tableName);
db.Insert(tableName, new GenericEntity { Id = 1, ColumnA = "A" });
var rows = db.Select<GenericEntity>(tableName, q =>
q.Where(x => x.ColumnA == "A"));
rows.PrintDump();
db.Update(tableName, new GenericEntity { ColumnA = "B" },
where: q => q.ColumnA == "A");
rows = db.Select<GenericEntity>(tableName, q =>
q.Where(x => x.ColumnA == "B"));
rows.PrintDump();
Run Code Online (Sandbox Code Playgroud)
此示例也可用于GenericTableExpressions.cs集成测试。
| 归档时间: |
|
| 查看次数: |
1471 次 |
| 最近记录: |