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

我可以在 .NET Core 类库中做类似的事情吗?我在将 System.Data.SqlClient 的引用添加到我的 .NET Core 类库时遇到问题,我不知道要添加什么。

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;
}
wangjingjun2007 回答:我可以在 .NET Core 中使用 List<T> 或 IEnumerable<T> 执行 ADO.NET 吗?

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

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

本文链接:https://www.f2er.com/304723.html

大家都在问