使用自定义名称动态创建 table 并使用自定义 table 名称插入

Create table with custom name dynamically and insert with custom table name

我想用自定义名称创建 table,但找不到示例代码。我注意到创建 table 的唯一方法是通过像 db.CreateTable() 这样的泛型类型。我可以知道是否有办法动态创建 table 名称而不是使用别名吗?原因是因为有时我们想将相同的对象类型存储到不同的 table 中,例如 2015_january_activity、2015_february_activity.

除此之外,db.Insert 对象类型也非常有限。无论如何要通过传入 table 名称来插入?

我认为这些特性非常重要,因为它长期存在于 NoSQL 解决方案中并且非常灵活。谢谢

OrmLite 主要是一个代码优先的 ORM,它使用类型化的 POCO 来创建和查询匹配 RDMBS table 的模式。它还支持使用 Custom SQL API's 执行自定义 SQL。

使用不同 table 名称的一个选项是在运行时将别名更改为 seen in this previous answer,您可以在其中创建自定义扩展方法来修改 table 的名称,例如:

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));
    }
}

这些扩展方法提供了额外的 API,可让您更改所用 table 的名称,例如:

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();

此示例也可用于 GenericTableExpressions.cs 集成测试。