【问题标题】:Create table with custom name dynamically and insert with custom table name动态创建具有自定义名称的表并使用自定义表名称插入
【发布时间】:2015-03-26 12:31:28
【问题描述】:

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

除此之外,db.Insert 还非常受限于对象类型。无论如何通过传入表名来插入?

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

【问题讨论】:

    标签: servicestack


    【解决方案1】:

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

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

    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,让您可以更改所用表的名称,例如:

    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 集成测试。

    【讨论】:

    • 感谢您的帮助。你拯救了我的一天。
    猜你喜欢
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    • 2017-02-18
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多