Skip to content

Instantly share code, notes, and snippets.

@babcca
Created January 29, 2014 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save babcca/fb12695dfee0049d70e7 to your computer and use it in GitHub Desktop.
Save babcca/fb12695dfee0049d70e7 to your computer and use it in GitHub Desktop.
Testing calling ormlite functions with type
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