Can I do something similar to this in a .NET Core Class Library? I'm having trouble adding a reference to System.Data.SqlClient to my .NET Core Class Library and I don't know what to add instead.
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;
}
Here's what it looks like in 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();
}
You just need a [Column(Name = "Person")]
on your C# Person's FirstName
property
(And add some error handling if you want - omitted for brevity)