【问题标题】:Can I do ADO.NET using List<T> or IEnumerable<T> in .NET Core?我可以在 .NET Core 中使用 List<T> 或 IEnumerable<T> 执行 ADO.NET 吗?
【发布时间】: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


【解决方案1】:

这是 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# Person 的 FirstName 属性上添加一个 [Column(Name = "Person")]

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 2015-10-22
    • 2015-11-19
    相关资源
    最近更新 更多