110,538
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 获取映射后类型为 T 的数据实体。
/// </summary>
/// <typeparam name="T">映射的数据实体对象类型。</typeparam>
/// <param name="commandText">针对数据源运行的文本命令。</param>
/// <param name="commandType">指示或指定如何解释 System.Data.IDbCommand.CommandText 属性。</param>
/// <param name="dataParameters">针对数据源运行的文本命令的参数集合。</param>
/// <exception cref="DbConverterException">执行数据读取器或数据映射到实体出错。</exception>
/// <returns>映射后类型为 T 的数据实体。</returns>
public T GetMappedDataEntity<T>(StringBuilder commandText, CommandType commandType, params IDataParameter[] dataParameters)
where T : INamingContainerEntity, new()
{
T t = default(T);
IDataReader dataReader = null;
try
{
IDictionary<string, PropertyInfo> properties = ExtractMappingDataAttribute<T, MappingDataFieldAttribute>.GetProperties();
if (properties != null && properties.Count > 0)
{
dataReader = this.ExecuteReader(commandType, commandText, dataParameters);
if (dataReader.Read())
{
t = SetPropertyValue<T>(dataReader, properties);
}
dataReader.Close();
this.MainConnection.Close();
}
}
catch (DbHelperException ex)
{
throw new DbConverterException(ex.Message, ex);
}
finally
{
if (dataReader != null && !dataReader.IsClosed)
dataReader.Close();
this.MainConnection.Close();
}
return t;
}
using(var reader =this.ExecuteReader(commandType, commandText, dataParameters) )
{
}
通过using自动释放,当然数据库连接的释放是另一回事情
if (properties != null && properties.Count > 0)
{
object locker = new object();
lock(locker)
{
dataReader = this.ExecuteReader(commandType, commandText, dataParameters);
if (dataReader.Read())
{
t = SetPropertyValue<T>(dataReader, properties);
}
}
//既然finally里面有close,这里貌似不用close
//dataReader.Close();
//this.MainConnection.Close();
}