-
-
Save babcca/fb12695dfee0049d70e7 to your computer and use it in GitHub Desktop.
Testing calling ormlite functions with type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BaseClass | |
{ | |
public int Id { get; set; } | |
public string A { get; set; } | |
} | |
class Record : BaseClass | |
{ | |
public string B { get; set; } | |
} | |
class MyTest | |
{ | |
public void Test(IDbConnection db) | |
{ | |
db.DropAndCreateTable<Record>(); | |
var type = typeof(Record); | |
var obj = Activator.CreateInstance(type); | |
var baseRecord = (BaseClass)(obj); | |
baseRecord.A = "a"; | |
try | |
{ | |
db.Insert(baseRecord); // Trying insert into BaseRecord instead of Record table | |
} | |
catch { } | |
try | |
{ | |
db.Insert(obj); // SQL Error | |
} | |
catch { } | |
try | |
{ | |
db.UpdateNonDefaults(baseRecord, r => r.A == "a"); // Trying insert into BaseRecord instead of Record table | |
} | |
catch { } | |
try | |
{ | |
db.UpdateNonDefaults(obj, r => ((BaseClass)r).A == "a"); // SQL Error | |
} | |
catch { } | |
// Now we must write own OrmLite methods wrapper because they are generic and overloaded. | |
// So they are hard to find them using c# generic | |
try | |
{ | |
CallGeneric("MyInsert", type, db, baseRecord, null); // Passs | |
} | |
catch { } | |
try | |
{ | |
// This is very bad because i need use Select (with where), etc. | |
Expression<Func<BaseClass, bool>> e = r => r.A == "a"; | |
CallGeneric("MyUpdate", type, db, baseRecord, e); // It can't convert Func<BaseClass, bool> into Func<Record, bool> | |
} | |
catch { } | |
} | |
public static void MyInsert<T>(IDbConnection db, T obj, Expression<Func<T, bool>> e = null) | |
where T : BaseClass | |
{ | |
db.Insert<T>(obj); | |
} | |
public static void MyUpdate<T>(IDbConnection db, T obj, Expression<Func<T, bool>> e = null) | |
where T : BaseClass | |
{ | |
db.UpdateNonDefaults<T>(obj, e); | |
} | |
public static object CallGeneric(string methodName, Type genericType, params object[] args) | |
{ | |
MethodInfo method = typeof(MyTest).GetMethod(methodName); | |
MethodInfo genericMethod = method.MakeGenericMethod(new Type[] { genericType }); | |
object data = genericMethod.Invoke(null, args); | |
return data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment