每次我运行下面的代码时,它都应该在数据库中找到任何名为“sam”的人,但我不只是想出一个人......
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;
}
和人是:
namespace Calculator.Models
{
public class Person
{
public string PersonId { get; set; }
public string Name { get; set; }
}
}
该查询有效,因为我已经在另一个程序上对其进行了多次测试。我认为错误来自:
info = new Person[] {new Person {PersonId = PersonID, Name = PersonName}};
因为它替换了 info 的整个值,我怎么会不替换整个值而只是添加它。