Spider Man Spider Man - 1 year ago 130
ASP.NET (C#) Question

How to combine two sql queries in one controller action in asp.net mvc?

In my asp.net mvc application, I have to fetch information about a page from two separate tables.

The queries are something like these:

string query = "select * from some_table1; select * from some_table2;"

Then the information from the tables is extracted using:

using(SqlConnection con = new SqlConnection(connectionString'))
SqlCommand cmd = new SqlCommand(query, con);
using(SqlDataReader reader = cmd.ExecuteReader())
// do the addition of data into a model

Do I have to parse / read the data twice to populate the data inside two different models. Or can it be done in one parse?


Answer Source

If you are going to get data by joining the tables you could have single model. Make it a single query by introducing the join.

If they are different datasets altogether, then you need two queries. If you are worried about opening/closing of two connections, you need not have to do it. Make use of CommandText

// Create the first command and execute
var command = new SqlCommand("<SQL Command>", connection);
var reader = command.ExecuteReader();

// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download