Return Result from Select Query in stored procedure to a List

前端 未结 8 2007
猫巷女王i
猫巷女王i 2021-01-01 10:10

I\'m writing a stored procedure that currently contains only a SELECT query. It will be expanded to do a number of other things, which is why it has to be a sto

8条回答
  •  鱼传尺愫
    2021-01-01 10:26

    Building on some of the responds here, i'd like to add an alternative way. Creating a generic method using reflection, that can map any Stored Procedure response to a List. That is, a List of any type you wish, as long as the given type contains similarly named members to the Stored Procedure columns in the response. Ideally, i'd probably use Dapper for this - but here goes:

    private static SqlConnection getConnectionString() // Should be gotten from config in secure storage.
            {
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                builder.DataSource = "it.hurts.when.IP";
                builder.UserID = "someDBUser";
                builder.Password = "someDBPassword";
                builder.InitialCatalog = "someDB";
                return new SqlConnection(builder.ConnectionString);
            }
    
            public static List ExecuteSP(string SPName, List Params)
            {
                try
                {
                    DataTable dataTable = new DataTable();
    
                    using (SqlConnection Connection = getConnectionString())
                    {
                        // Open connection
                        Connection.Open();
    
                        // Create command from params / SP
                        SqlCommand cmd = new SqlCommand(SPName, Connection);
    
                        // Add parameters
                        cmd.Parameters.AddRange(Params.ToArray());
                        cmd.CommandType = CommandType.StoredProcedure;
    
                        // Make datatable for conversion
                        SqlDataAdapter da = new SqlDataAdapter(cmd);
                        da.Fill(dataTable);
                        da.Dispose();
    
                        // Close connection
                        Connection.Close();
                    }
    
                    // Convert to list of T
                    var retVal = ConvertToList(dataTable);
                    return retVal;
                }
                catch (SqlException e)
                {
                    Console.WriteLine("ConvertToList Exception: " + e.ToString());
                    return new List();
                }
            }
    
            /// 
            /// Converts datatable to List if possible.
            /// 
            public static List ConvertToList(DataTable dt)
            {
                try // Necesarry unfotunately.
                {
                    var columnNames = dt.Columns.Cast()
                        .Select(c => c.ColumnName)
                        .ToList();
    
                    var properties = typeof(T).GetProperties();
    
                    return dt.AsEnumerable().Select(row =>
                        {
                            var objT = Activator.CreateInstance();
    
                            foreach (var pro in properties)
                            {
                                if (columnNames.Contains(pro.Name))
                                {
                                    if (row[pro.Name].GetType() == typeof(System.DBNull)) pro.SetValue(objT, null, null);
                                    else pro.SetValue(objT, row[pro.Name], null);
                                }
                            }
    
                            return objT;
                        }).ToList();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to write data to list. Often this occurs due to type errors (DBNull, nullables), changes in SP's used or wrongly formatted SP output.");
                    Console.WriteLine("ConvertToList Exception: " + e.ToString());
                    return new List();
                }
            }
    

    Gist: https://gist.github.com/Big-al/4c1ff3ed87b88570f8f6b62ee2216f9f

提交回复
热议问题