I have a bunch of DAO classes that do something similar for an Entity. I was wondering if anyone can help me with ways to: 1) Simplify this code 2) Stop from duplicating code like this for each entity.
public IList<IUser> GetAll()
{
IList<IUser> users = new List<IUser>();
using (var myConnection = new SqlConnection(ApplicationConfig.ConnectionString))
{
using (var myCommand = new SqlCommand("sp_GetAllUsers", myConnection))
{
myCommand.CommandType = CommandType.StoredProcedure;
myConnection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader())
{
if (myReader != null)
{
while (myReader.Read())
users.Add(FillDataRecord(myReader));
myReader.Close();
}
}
}
myConnection.Close();
}
return users;
}
public IUser GetBy(int id)
{
IUser user = null;
using (var myConnection = new SqlConnection(AppConfiguration.ConnectionString))
{
using (var myCommand = new SqlCommand("sp_GetUserById", myConnection))
{
myCommand.Parameters.Add("@id", System.Data.SqlDbType.Int).Value = id;
myCommand.CommandType = CommandType.StoredProcedure;
myConnection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader())
{
if (myReader != null)
{
while (myReader.Read())
user = FillDataRecord(myReader);
myReader.Close();
}
}
}
myConnection.Close();
}
return user;
}
private static IUser FillDataRecord(IDataRecord myDataRecord)
{
IAddress address = null;
if (!myDataRecord.IsDBNull(myDataRecord.GetOrdinal("AddressId")))
address= GetAddress(myDataRecord.GetInt32(myDataRecord.GetOrdinal("AddressId")));
IUser user = new User
{
Id = myDataRecord.GetInt32(myDataRecord.GetOrdinal("Id"))
,LastName = myDataRecord.IsDBNull(myDataRecord.GetOrdinal("LastName")) ? string.Empty : myDataRecord.GetString(myDataRecord.GetOrdinal("LastName"))
,FirstName = myDataRecord.IsDBNull(myDataRecord.GetOrdinal("FirstName")) ? string.Empty : myDataRecord.GetString(myDataRecord.GetOrdinal("FirstName"))
,MyAddress= address
};
return user;
}
Thanks in advance