1+ using System ;
2+ using System . Collections . Generic ;
3+ using System . Data ;
4+ using System . Linq . Expressions ;
5+ using NUnit . Framework ;
6+ using ServiceStack . DataAnnotations ;
7+ using ServiceStack . Logging ;
8+
9+ namespace ServiceStack . OrmLite . Tests . Expression
10+ {
11+ public class GenericEntity
12+ {
13+ public int Id { get ; set ; }
14+
15+ [ Alias ( "COL_A" ) ]
16+ public string ColumnA { get ; set ; }
17+ }
18+
19+ [ TestFixture ]
20+ public class GenericTableExpressions : OrmLiteTestBase
21+ {
22+ [ Test ]
23+ public void Can_change_table_at_runtime ( )
24+ {
25+ LogManager . LogFactory = new ConsoleLogFactory ( ) ;
26+
27+ const string tableName = "Entity1" ;
28+ using ( var db = OpenDbConnection ( ) )
29+ {
30+ db . DropAndCreateTable < GenericEntity > ( tableName ) ;
31+
32+ db . Insert ( tableName , new GenericEntity { Id = 1 , ColumnA = "A" } ) ;
33+
34+ var rows = db . Select < GenericEntity > ( tableName , q =>
35+ q . Where ( x => x . ColumnA == "A" ) ) ;
36+
37+ Assert . That ( rows . Count , Is . EqualTo ( 1 ) ) ;
38+
39+ db . Update ( tableName , new GenericEntity { ColumnA = "B" } ,
40+ where : q => q . ColumnA == "A" ) ;
41+
42+ rows = db . Select < GenericEntity > ( tableName , q =>
43+ q . Where ( x => x . ColumnA == "B" ) ) ;
44+
45+ Assert . That ( rows . Count , Is . EqualTo ( 1 ) ) ;
46+ }
47+ }
48+ }
49+
50+ public static class GenericTableExtensions
51+ {
52+ static object ExecWithAlias < T > ( string table , Func < object > fn )
53+ {
54+ var modelDef = typeof ( T ) . GetModelMetadata ( ) ;
55+ lock ( modelDef )
56+ {
57+ var hold = modelDef . Alias ;
58+ try
59+ {
60+ modelDef . Alias = table ;
61+ return fn ( ) ;
62+ }
63+ finally
64+ {
65+ modelDef . Alias = hold ;
66+ }
67+ }
68+ }
69+
70+ public static void DropAndCreateTable < T > ( this IDbConnection db , string table )
71+ {
72+ ExecWithAlias < T > ( table , ( ) => {
73+ db . DropAndCreateTable < T > ( ) ;
74+ return null ;
75+ } ) ;
76+ }
77+
78+ public static long Insert < T > ( this IDbConnection db , string table , T obj , bool selectIdentity = false )
79+ {
80+ return ( long ) ExecWithAlias < T > ( table , ( ) => db . Insert ( obj , selectIdentity ) ) ;
81+ }
82+
83+ public static List < T > Select < T > ( this IDbConnection db , string table , Func < SqlExpression < T > , SqlExpression < T > > expression )
84+ {
85+ return ( List < T > ) ExecWithAlias < T > ( table , ( ) => db . Select ( expression ) ) ;
86+ }
87+
88+ public static int Update < T > ( this IDbConnection db , string table , T item , Expression < Func < T , bool > > where )
89+ {
90+ return ( int ) ExecWithAlias < T > ( table , ( ) => db . Update ( item , where ) ) ;
91+ }
92+ }
93+ }
0 commit comments