Return objects with populated list properties from stored procedure

后端 未结 2 1665
深忆病人
深忆病人 2021-01-26 09:10

I\'m new to SQL Server stored procedures, so apologies if I\'m being an idiot. I would like to use a stored procedure to return a list of objects, each of which has a property c

2条回答
  •  面向向阳花
    2021-01-26 10:08

    Actually a stored procedure delivers a relational result rather than objects. As an alternative, you could return XML using FOR XML and deserialize it into objects. Mapping this to objects is usually done using an O/R mapper.

    You can use datasets and table adapters to get the relational data into your applications. Once loaded into the dataset, you can populate your Question and Answer objects.

    Here is a sample toy code to fill the result of a stored procedure into a data set:

    var ds = new DataSet();
    
    using (var cn = new SqlConnection())
    using (var cmd = new SqlCommand("myStoredProcedure", cn))
    {
        cmd.CommandType = CommandType.StoredProcedure;
    
        using (var adapter = new SqlDataAdapter(cmd))
        {
            adapter.TableMappings.Add("Table0", "Answers");
            adapter.TableMappings.Add("Table1", "Questions");
    
            adapter.Fill(ds);
        }
    }
    

    For actual development I'd suggest you to use a Typed Dataset and a proper SqlConnection. However, as comments pointed out too, use EF or another O/R mapper if you can.

提交回复
热议问题