【发布时间】:2021-08-23 00:05:36
【问题描述】:
我可以在 .NET Core 类库中做类似的事情吗?我在向我的 .NET Core 类库添加对 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;
}
【问题讨论】:
-
对于新项目,您可能应该使用Microsoft.Data.SqlClient。
-
是的,System.Data.SqlClient 现在实际上已经过时了。
-
你也可以通过安装 Dapper 跳过你写的所有代码
-
您应该使用
using块处理您的对象
标签: c# .net-core ado.net data-access-layer data-access