我可以在 .NET Core 中使用 List<T> 或 IEnumerable<T> 来执行 ADO.NET 吗?
Can I do ADO.NET using List<T> or IEnumerable<T> in .NET Core?
我可以在 .NET Core Class 库中做类似的事情吗?我在将对 System.Data.SqlClient 的引用添加到我的 .NET Core Class 库时遇到问题,我不知道该添加什么。
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")]
(并根据需要添加一些错误处理 - 为简洁起见省略)
我可以在 .NET Core Class 库中做类似的事情吗?我在将对 System.Data.SqlClient 的引用添加到我的 .NET Core Class 库时遇到问题,我不知道该添加什么。
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")]
(并根据需要添加一些错误处理 - 为简洁起见省略)