Every time I run the code below it is supposed to come up with anyone with the name of “sam” in the database but it doesn’t i just comes up with one person…
public IEnumerable<Person> GetPersons(string name)
{
string PersonID;
string PersonName;
var info = new Person[] {};
try
{
string connectionString =
@"Password=nottelling;Persist Security Info=True;User ID=nottelling;Initial Catalog=customers;Data Source=db.example.com;";
using (var connection = new SqlConnection(connectionString))
{
string command = string.Format(@"SELECT Fname, PersonID, Lname FROM Person Where Fname = '{0}'",name);
connection.Open();
var getperson = new SqlCommand(command, connection);
SqlDataReader reader = getperson.ExecuteReader();
while (reader.Read())
{
PersonID = reader["PersonID"].ToString();
PersonName = reader["Fname"].ToString();
PersonName += " ";
PersonName += reader["Lname"].ToString();
info = new Person[] {new Person {PersonId = PersonID, Name = PersonName}};
}
connection.Close();
}
}
catch (Exception ex)
{
PersonID = "Error:";
PersonName = ex.Message;
info = new[] {new Person {PersonId = PersonID, Name = PersonName}};
}
return info;
}
and Person is :
namespace Calculator.Models
{
public class Person
{
public string PersonId { get; set; }
public string Name { get; set; }
}
}
The query works because I already tested it multiple times on another program.
I think the error is from :
info = new Person[] {new Person {PersonId = PersonID, Name = PersonName}};
because it replaces the whole value of info how would I not replace the whole value and just add to it.
UPDATE: As recommended by DanC, I have changed the array type
You are assigning a brand new array each time… You should be adding to the array… Look at using something like the
ArrayListclass for ease of useInstead of…
Change to…
Instead of…
Change to…
Instead of…
Change to…