The best solution I could find (anywhere) to get results from an SQL Query into a local variable was to use a NULL List<dynamic> or IEnumerable<dynamic> variable declaration.
Creating the variable by doing something like:
@{
IEnumerable<dynamic> myVariable = null;
}
The variable can then get a value from a database query like:
@{
try
{
Database db = Database.Open("name"); // name of connectionString configured in web.config
string myQuery = "EXEC dbo.Get_Results @Param1=@0, @Param2=@1";
myVariable = db.Query(myQuery, @Param1, @Param2);
db.Close();
db.Dispose();
}
catch (Exception ex)
{
// Do something
}
Which allows me to do something like the following:
@if(myVariable != null)
{
foreach (var row in myVariable)
{
// Do something
}
}
This is working perfectly, but what I am still curious is how to do the same using List<dynamic>, as an alternative to using IEnumerable<dynamic> the way I am using it.
What is the List<dynamic> equivalent solution that I am using for IEnumerable<dynamic>?
I know my question itself is very simple, but it took me a long time to get past trying to solve can’t implicitly convert errors when I tried to create a Class that could receive the results from db.Query(commandText) into a pre-declared variable. So I thought I should provide more detail in case this helps someone else trying to figure out the same or similar. I found my solution on the IEnumerable<dynamic> in unrelated topic which opened my eyes to much simpler solution to problem I was trying to solve.
Enumerable.Empty<string>()is not null. It is an empty sequence of strings. Note, for example, that the following code prints “false”:You probably want to create a new (empty) list:
or, if you really need the list variable to hold a null reference: