///
///执行mysql原生语句///
/// 查询返回结果的Dto
/// MySQL语句
/// 超时时间
/// MySQLParameter 参数防止sql注入
/// 返回结果Dto的集合
public IList SqlQuery(string mysql, int? timeOutNum = null, params object[] parameters)where TEntity : new()
{//注意:不要对GetDbConnection获取到的conn进行using或者调用Dispose,否则DbContext后续不能再进行使用了,会抛异常
var conn =db.Database.GetDbConnection();try{
conn.Open();using (var command =conn.CreateCommand())
{if(timeOutNum.HasValue)
{
command.CommandTimeout=timeOutNum.Value;
}
command.CommandText=mysql;if (parameters.Count() > 0)
{
command.Parameters.AddRange(parameters);
}var propts = typeof(TEntity).GetProperties();var rtnList = new List();
TEntity model;objectval;using (var reader =command.ExecuteReader())
{while(reader.Read())
{
model= newTEntity();foreach (var l inpropts)
{
val=reader[l.Name];if (val ==DBNull.Value)
{
l.SetValue(model,null);
}else{
l.SetValue(model, val);
}
}
rtnList.Add(model);
}
}returnrtnList;
}
}finally{
conn.Close();
}
}