.net下开源轻量级ORM框架Dapper扩展系列3
按条件删除:
复制代码
/// <summary>
/// 按条件删除
/// </summary>
/// <typeparam name="t"></typeparam>
/// <param name="dbs"></param>
/// <param name="sql"></param>
/// <returns></returns>
public static bool delete<t>(this dbbase dbs, sqlquery sql = null) where t : class
{
var result = false;
var db = dbs.dbconnecttion;
var tbname = common.gettablename<t>();
var sqlstr = "";
if (sql == null)
{
sqlstr = string.format("delete from {0}", tbname);
}
else
{
sqlstr = string.format("delete from {0} {1}", tbname, sql.sql);
}
var f = -1;
if (sql == null)
{
f = db.execute(sqlstr);
}
else
{
f = db.execute(sqlstr, sql.param);
}
result = f > 0;
return result;
}
复制代码
修改:
复制代码
/// <summary>
/// 修改
/// </summary>
/// <typeparam name="t"></typeparam>
/// <param name="dbs"></param>
/// <param name="t">如果sql为null,则根据t的主键进行修改</param>
/// <param name="sql">按条件修改</param>
/// <returns></returns>
public static bool update<t>(this dbbase dbs, t t, sqlquery sql = null) where t : class
{
var result = false;
var db = dbs.dbconnecttion;
var tbname = common.gettablename<t>();
var columns = common.getexeccolumns<t>();
var sqlstr = "";
var upsql = "";
var f = -1;
if (sql == null)
{
var propertyname = "";
var columkey = common.getprimarykey<t>(out propertyname);
var noupdatecolums = new list<string>() { columkey };
upsql = createupdatesql(tbname, columns, dbs.paramprefix, noupdatecolums);
sqlstr = string.format("{0} where {1}={2}", upsql, columkey, dbs.paramprefix + propertyname);
f = db.execute(sqlstr, t);
}
else
{
var propertyname = "";
var columkey = common.getprimarykey<t>(out propertyname);
var noupdatecolums = new list<string>() { columkey };
upsql = createupdatesql(tbname, columns, dbs.paramprefix, noupdatecolums);
sqlstr = string.format("{0} {1}", upsql, sql.sql);
var parammodel = createupdatemodel<t>(t, sql.param);
f = db.execute(sqlstr, parammodel);
}
result = f > 0;
return result;
}
复制代码
获取默认一条数据:
复制代码
/// <summary>
/// 获取默认一条数据,没有则为null
/// </summary>
/// <typeparam name="t"></typeparam>
/// <param name="dbs"></param>
/// <param name="sql"></param>
/// <returns></returns>
public static t singleordefault<t>(this dbbase dbs, sqlquery sql) where t : class
{
var db = dbs.dbconnecttion;
var result = new list<t>();
sql = sql.top(1);
var sqlstr = createquerysql<t>(dbs, sql);
if (sql == null || sql.param == null)
{
result = db.query<t>(sqlstr).tolist();
}
else
{
result = db.query<t>(sqlstr, sql.param).tolist();
}
return result.firstordefault();
}
复制代码