Reputation: 60
I am converting data from sql into a list of PersonModel. But my question is: is there a faster way ( less code ) to get this done without using any framework / dapper. LINQ is ALLOWED.
( The code right now is just working fine, but maybe it can be done in a simpler way ).
This is the code I have right now:
public List<PersonModel> GetPerson_All()
{
var people = new List<PersonModel>();
//Get the connectionString from appconfig
using (var connection = new SqlConnection(GlobalConfig.CnnString(db)))
{
connection.Open();
//Using the stored procedure in the database.
using (var command = new SqlCommand("dbo.spPeople_GetAll", connection))
{
using (var reader = command.ExecuteReader())
{
//With a while loop, going trough each row to put all the data in the PersonModel class.
while (reader.Read())
{
var person = new PersonModel();
person.Id = (int)reader["Id"];
person.FirstName = (string) reader["FirstName"];
person.LastName = (string)reader["LastName"];
person.EmailAdress = (string)reader["EmailAddress"];
person.CellphoneNumber = (string)reader["CellphoneNumber"];
//Add the data into a list of PersoModel
people.Add(person);
}
}
}
}
return people;
}
With ( dapper ) you can put all the data inmediatly to a list. Is something like this possible without dapper?
public List<PersonModel> GetPerson_All()
{
List<PersonModel> output;
using (var connection = new SqlConnection(GlobalConfig.CnnString(db)))
{
output = connection.Query<PersonModel>("dbo.spPeople_GetAll").ToList();
}
return output;
}
Upvotes: 1
Views: 613
Reputation: 157126
No, there is not an more optimal way to do this then to use a method or mapper library like Dapper or Entity Framework: that is the entire reason such libraries exist.
If you have repeating code blocks like this, but don't want to use external libraries, you can try to refactor this to a method which executes a statement, iterates over the result and instantiates and fills objects.
Upvotes: 2