.NET 使用SQL和T类生成SQL参数列表-仅一级属性值

public static (List<SqlParameter> ListParameter, string Error) MakeSQLParamterListFromSQLAndClass<T>(string strSQL, T MyCls)
{

List<SqlParameter> lsSP = new List<SqlParameter>();
string strError = "";
try
{
if (!string.IsNullOrWhiteSpace(strSQL) && MyCls != null)
{
#region
PropertyInfo[] cProperties = MyCls.GetType().GetProperties();//得到一级全部属性值
string strPattern = @"\@\w+\b";
MatchCollection mc = Regex.Matches(strSQL, strPattern);
List<string> lsParamter = new List<string>();//全部参数
foreach (var mp in mc)
{
if (!string.IsNullOrWhiteSpace(mp.ToString()))
{
lsParamter.Add(mp.ToString());

}
}
lsParamter = lsParamter.Distinct().ToList();//去重复数据
List<PropertyInfo> lsPropertyInfo = cProperties.ToList();//转为List

foreach (string Paramter in lsParamter)
{
string strParamterName = Paramter.Replace("@", "");//去掉头@
bool bHasValue = false;
foreach (PropertyInfo ProInfo in lsPropertyInfo)
{
if (
ProInfo.PropertyType == typeof(string)
|| ProInfo.PropertyType == typeof(long?)
|| ProInfo.PropertyType == typeof(DateTime?)
|| ProInfo.PropertyType == typeof(decimal?)
)
{
#region
if (ProInfo.Name.Equals(strParamterName))
{
bHasValue = true;//有参数值

if (ProInfo.PropertyType == typeof(string))
{
string objValue = ProInfo.GetValue(MyCls) as string;
//lsSP.Add(new SqlParameter(Paramter, objValue));
lsSP.Add(clsBase.MakeSqlParameter(Paramter, objValue));
}
else if (ProInfo.PropertyType == typeof(long?))
{
long? objValue = ProInfo.GetValue(MyCls) as long?;
lsSP.Add(new SqlParameter(Paramter, objValue.HasValue ? objValue.Value : DBNull.Value));
}
else if (ProInfo.PropertyType == typeof(DateTime?))
{
DateTime? objValue = ProInfo.GetValue(MyCls) as DateTime?;
lsSP.Add(new SqlParameter(Paramter, objValue.HasValue ? objValue.Value : DBNull.Value));
}
else if (ProInfo.PropertyType == typeof(decimal?))
{
decimal? objValue = ProInfo.GetValue(MyCls) as decimal?;
lsSP.Add(new SqlParameter(Paramter, objValue.HasValue ? objValue.Value : DBNull.Value));
}

lsPropertyInfo.Remove(ProInfo);//移除使用过的数据
break;
}
#endregion
}
else
{
//不处理其它类型的数据
}


}
if (!bHasValue)
{
strError += "类中未找到参数[" + strParamterName + "];";
}

}

#endregion
}
else
{
//空值不处理
}
}
catch (Exception ex)
{
strError += ex.Message;
}
if (!string.IsNullOrWhiteSpace(strError))
{
strError = "FullClassName[" + typeof(T).FullName + "];" + strError;
}
return (lsSP, strError);
}

var temp = MakeSQLParamterListFromSQLAndClass<Class>(strSQL, class); 

//strSQL执行SQL语句,Class类,class类的对象

posted @ 2022-07-04 17:46  御翼仁粨狩  阅读(72)  评论(0)    收藏  举报