1

ASP.NET MVC 2 + SQL Server Express...

2 Answers 2

3

The same way you would in every .NET application:

using (var connection = new SqlConnection("PUT YOUR CONNECTION STRING HERE"))
using (var command = connection.CreateCommand())
{
    connection.Open();
    command.CommandText = "SELECT id FROM table";
    using (var reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            // TODO: read the results
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

As Darin pointed out, it's the same as any other .NET application.

However, it's worth noting that it should really be done as part of an Action inside of a Controller, not directly in your view. The Web Forms way is like having the View and Controller wrapped into one object.

One of the goals of the MVC pattern is to separate your view, controller and model so the views are free to display their data without worrying about where it came from or how it got there. The controllers deal with assembling that data ready for the view to display and the models are used as the data layer populated by the controller and given to the view to display.

1 Comment

Without knowing what the OP is intending it's hard to comment, but I would normally try and keep all my database access code in an appropriate method in my Model rather than directly in the Controller. As you say, this would be called from an Action method in the Controller at some point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.