I have an SQL query within ASP.NET, but it only seems to return 1 result rather than filling the list with 4 as it should (as the query itself is correct)

Code:

List<string> dropItems, dropItems2;

using (var dbContext = new DatabaseContext())
{
    dropItems = dbContext.Database.SqlQuery<String>(
        String.Format("SELECT locations.Code FROM locations")).ToList();
}
using (var dbContext = new DatabaseContext())
{
    dropItems2 = dbContext.Database.SqlQuery<String>(
        String.Format("SELECT locations.Name FROM locations")).ToList();
}

After the code executes, each list only contains one item rather than 4 which they both should

Have you tried a more conventional way to populate those lists?
Like iterating through the rows. Just to check to see if you do get 4 records instead of 1.
Have you also tried declaring those lists as new?

I don't see anything wrong with your code. as depicted in your code snippet above try inserting a breakpoint on lines 5,10 and hover over dropItems and dropItems2 it should display a count which should be 4 if the database returned more than 4 rows. Try pasting and running the query in SQL and see how many record are returned to ensure the data is correct.

You should be following the advice of Oxiegen and see the behaviour after the iteration. Otherwise, please post a little bit more of the actual code. Also on every postback your list variable is destroyed (there are no public variables in ASP.Net) I'm talking about webforms (do not have expirience with MVC, but i think that this is not the case with MVC) but that shouldn't be the problem here. One other thing, which object are you actually using to display your list??

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.