使用自定义返回类型从数据库获取数据的常用方法,数据访问层C#

时间:2014-12-20 13:06:04

标签: c# .net c#-4.0

在我的数据访问层中,我有一个名为Execute的类。 class Execute用于与数据库进行事务。

我有另一个名为Table1DataAceess的类与Execute类进行通信,BusinessLogicClass1与数据访问层进行通信。例如:图片

enter image description here

我只有4种方法与数据库进行任何交易(插入,更新,删除,检索)。 在Retrieving方法中,我想实现获取任何返回类型而不预先定义返回类型。

例如:如果我想获取一个VehicleModel数据列表,在我的Table1DataAceess类中,我只需要编写

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);

我开发了以下方法,

 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;
        }
    } 

我不知道如何使用数据创建此返回类型“T”。因为如果它是一个列表,那么我必须填写列表并返回列表。 (方法应该将T作为列表返回)但是如何将列表创建为T。

请帮助..

1 个答案:

答案 0 :(得分:2)

这是一个例子

这是DbAccess图层的方法。这个方法将执行readader,你甚至可以填充数据表并将其转换为列表。

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
        {


        }

    }

这是将数据表或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;

    }
}

以下是您将如何称呼它

 List<YourClassName> list = DbAccess.ReturnList<YourClassName>(System.Data.CommandType.StoredProcedure, "searchappointments", listParams);