Inject TableName as Parameter for Update & Insert on GenericEntity in ServiceStack Ormlite

前端 未结 1 1856
深忆病人
深忆病人 2021-01-07 09:55

I have 3 tables of same structure so i have created the following entity using ServiceStack

public class GenericEntity
{
    [Alias(\"COL_A\")]
    public st         


        
相关标签:
1条回答
  • 2021-01-07 10:19

    As you're wanting to this for multiple API's I've added a test showing how to achieve the desired behavior by extending OrmLite's API's with your own custom extension methods that modifies OrmLite's table metadata at runtime to add new API's that allow specifying the table name at runtime, i.e:

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

    With these extension methods:

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

    Adding your own extension methods in this way allows you to extend OrmLite with your own idiomatic API's given that OrmLite is itself just a suite of extension methods over ADO.NET's IDbConnection.

    0 讨论(0)
提交回复
热议问题