从具有自定义返回类型的数据库中获取数据的常用方法,数据访问层C#
在我的数据访问层中,我有一个名为从具有自定义返回类型的数据库中获取数据的常用方法,数据访问层C#,c#,.net,c#-4.0,C#,.net,C# 4.0,在我的数据访问层中,我有一个名为Execute的类。类Execute用于与数据库进行事务处理 我有另一个名为table1dataacess的类与Execute类通信,还有BusinessLogicClass1与数据访问层通信。例如:图片 我只有4种方法来处理数据库的任何事务(插入、更新、删除、检索)。 在检索方法中,我想实现在不预先定义返回类型的情况下获取任何返回类型 如果我想在Table1Dataace类中获得车辆模型数据列表,我只需要编写 Execute DBExe = new Execu
Execute
的类。类Execute
用于与数据库进行事务处理
我有另一个名为table1dataacess
的类与Execute类通信,还有BusinessLogicClass1
与数据访问层通信。例如:图片
我只有4种方法来处理数据库的任何事务(插入、更新、删除、检索)。
在检索方法中,我想实现在不预先定义返回类型的情况下获取任何返回类型
如果我想在Table1Dataace类中获得车辆模型数据列表,我只需要编写
Execute DBExe = new Execute();
List<VehicleModel> vList = DBExe<List<VehicleModel>,VehicleModel>(spName,model);
//If I wanna take it into a DataTable
DataTable dt = DBExe<DataTable,VehicleModel>(spName,model);
executedbexe=newexecute();
列表vList=DBExe(spName,型号);
//如果我想把它放到数据表中
数据表dt=DBExe(spName,型号);
在那里,我开发了以下方法
public T SpExecutesNew<T,T1>(string cmdText, T1 item) where T : new()
{
DataSet ds = new DataSet();
SqlDataAdapter ad = new SqlDataAdapter();
SqlCmd = new SqlCommand();
SqlConnection conn = null;
try
{
conn = clsConnection.OpenConnectiion();
SqlCmd.Connection = conn;
SqlCmd.CommandText = cmdText;
SqlCmd.CommandType = CommandType.StoredProcedure;
SqlCmd.CommandTimeout = 100;
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
SqlCommandBuilder.DeriveParameters(SqlCmd);
foreach (SqlParameter prr in SqlCmd.Parameters)
{
bool found = false;
if (prr.ParameterName.ToUpper() == "@RETURN_VALUE")
continue;
for (int i = 0; i < Props.Length && !found; i++)
{
string prName = "@" + Props[i].Name;
if (prr.ParameterName == prName)
{
prr.Value = Props[i].GetValue(item, null);
found = true;
}
}
}
ad = new SqlDataAdapter(SqlCmd);
ad.Fill(ds);
//List<T> list = new List<T>();
///STIL IMPLIMENTING...
////return (T)Convert.ChangeType(ds.Tables[0], typeof(T));
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (conn != null && conn.State == ConnectionState.Open)
conn.Close();
if (conn != null)
conn.Dispose();
SqlCmd = null;
}
}
public T SpExecutesNew(字符串cmdText,T1项),其中T:new()
{
数据集ds=新数据集();
SqlDataAdapter ad=新的SqlDataAdapter();
SqlCmd=newsqlcommand();
SqlConnection-conn=null;
尝试
{
conn=clsConnection.openconnection();
SqlCmd.Connection=conn;
SqlCmd.CommandText=cmdText;
SqlCmd.CommandType=CommandType.StoredProcess;
SqlCmd.CommandTimeout=100;
PropertyInfo[]Props=typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
派生参数(SqlCmd);
foreach(SqlCmd.Parameters中的SqlParameter prr)
{
bool-found=false;
if(prr.ParameterName.ToUpper()==“@返回值”)
继续;
对于(int i=0;i
我不知道如何使用数据创建此返回类型“T”。因为如果它是一个列表,那么我必须填写列表并作为列表返回。
(方法应将T作为列表返回)但如何将列表创建为T。
请帮助..以下是一个示例
这是DbAccess层的方法。这个方法将被executereader执行,您甚至可以填充datatable并将其转换为list
public List<T> ReturnList<T>(CommandType commandType, string commandText, List<SqlParameter> parameters) where T : new()
{
SqlDataReader reader = null;
try
{
CreateConnection();
command = new SqlCommand();
BuildCommand(command, commandType, commandText, conn);
AddParametersToCommand(parameters, command);
reader = command.ExecuteReader();
List<T> list = CommonMethods.ToList<T>(reader);
reader.Close();
reader.Dispose();
CloseConnection();
return list;
}
catch (Exception ex)
{
reader.Close();
reader.Dispose();
conn.Close();
throw ex;
}
finally
{
}
}
public List ReturnList(CommandType CommandType,string commandText,List参数),其中T:new()
{
SqlDataReader=null;
尝试
{
CreateConnection();
command=newsqlcommand();
BuildCommand(命令、命令类型、命令文本、conn);
AddParametersToCommand(参数,命令);
reader=command.ExecuteReader();
列表=CommonMethods.ToList(读卡器);
reader.Close();
reader.Dispose();
CloseConnection();
退货清单;
}
捕获(例外情况除外)
{
reader.Close();
reader.Dispose();
康涅狄格州关闭();
掷骰子;
}
最后
{
}
}
这是将datatable或sqldatareader转换为任何给定类列表的代码
CommonMethods.Cs
public static class CommonMethods
{
public static List<T> ToList<T>(DataTable datatable) where T : new()
{
List<T> Temp = new List<T>();
try
{
List<string> columnsNames = new List<string>();
foreach (DataColumn DataColumn in datatable.Columns)
columnsNames.Add(DataColumn.ColumnName);
Temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => getObject<T>(row, columnsNames));
return Temp;
}
catch { return Temp; }
}
private static T getObject<T>(DataRow row, List<string> columnsName) where T : new()
{
T obj = new T();
try
{
string columnname = "";
string value = "";
PropertyInfo[] Properties; Properties = typeof(T).GetProperties();
foreach (PropertyInfo objProperty in Properties)
{
columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());
if (!string.IsNullOrEmpty(columnname))
{
value = row[columnname].ToString();
if (!string.IsNullOrEmpty(value))
{
if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
{
value = row[columnname].ToString().Replace("$", "").Replace(",", "");
objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
}
else
{
value = row[columnname].ToString().Replace("%", "");
objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
}
}
}
} return obj;
}
catch { return obj; }
}
public static List<T> ToList<T>(SqlDataReader dataReader) where T : new()
{
List<T> res = new List<T>();
while (dataReader.Read())
{
T t = new T();
for (int inc = 0; inc < dataReader.FieldCount; inc++)
{
Type type = t.GetType();
PropertyInfo prop = type.GetProperty(dataReader.GetName(inc));
prop.SetValue(t, dataReader.GetValue(inc), null);
}
res.Add(t);
}
return res;
}
}
CommonMethods.Cs
公共静态类公共方法
{
公共静态列表ToList(DataTable DataTable),其中T:new()
{
列表温度=新列表();
尝试
{
列表列名称=新列表();
foreach(datatable.Columns中的DataColumn DataColumn)
columnsNames.Add(DataColumn.ColumnName);
Temp=datatable.AsEnumerable().ToList().ConvertAll(行=>getObject(行,列名称));
返回温度;
}
catch{return Temp;}
}
私有静态T getObject(DataRow行,List columnsName),其中T:new()
{
T obj=新的T();
尝试
{
字符串columnname=“”;
字符串值=”;
PropertyInfo[]Properties;Properties=typeof(T).GetProperties();
foreach(PropertyInfo对象属性在属性中)
{
columnname=columnsName.Find(name=>name.ToLower()==objProperty.name.ToLower());
如果(!string.IsNullOrEmpty(columnname))
{
值=行[columnname].ToString();
如果(!string.IsNullOrEmpty(值))
{
if(Nullable.GetUnderlineType(objProperty.PropertyType)!=null)
{
value=row[columnname].ToString().Replace(“$”,”).Replace(“,”,”);
objProperty.SetValue(obj,Convert.ChangeType(value,Type.GetType(Nullable.getUnderlineType(objProperty.PropertyType.ToString())),null);
}
其他的
{
value=行[columnname].ToString().Replace(“%”,“”);
SetValue(obj,Convert.ChangeType(value,Type.GetType(objProperty.PropertyType.ToString()),null);
List<YourClassName> list = DbAccess.ReturnList<YourClassName>(System.Data.CommandType.StoredProcedure, "searchappointments", listParams);