我可以在<T> .NET Core 中使用 List 或 IEnumerable 执行 ADO.NET<T> 吗?



我可以在.NET核心类库中执行类似的操作吗?我在向.NET核心类库添加对System.Data.SqlClient的引用时遇到问题,我不知道该添加什么。

public static List<Person> GetByLastName(string lastName)
{
List<Person> people = new List<Person>();
SqlConnection connection = new SqlConnection("connectionString");
SqlCommand cmd = new SqlCommand("usp_myStoredProcedure", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@lastName", lastName);
SqlDataReader dr = null;
try
{
connection.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
Person person = new Person();
person.FirstName = dr["Person"].ToString();
person.LastName = dr["LastName"].ToString();
person.PersonID = (int)dr["PersonID"];
people.Add(person);
}
}
catch (Exception ex)
{
// Log Error
throw ex;
}
finally
{
if (connection.State != ConnectionState.Closed)
connection.Close();
if (dr != null && !dr.IsClosed)
dr.Close();
}
return people;
}

以下是Dapper:中的内容

public static List<Person> GetByLastName(string lastName)
{
using connection = new SqlConnection("connectionString");
return connection.Query<Person>("usp_myStoredProcedure", new { lastName }, commandType: CommandType.StoredProcedure).ToList();
}

您只需要在C#人员的FirstName属性上使用[Column(Name = "Person")]

(如果需要,还可以添加一些错误处理-为简洁起见,省略(

最新更新