.net
-
while (rdr.Read())
{
// emp = new EmployeeBll(rdr["ID"].ToString(), rdr["Name"].ToString(), rdr["Gender"].ToString(), rdr["Email"].ToString(), rdr["Roles"].ToString());emp.ID = rdr\["ID"\].ToString(); emp.Name = rdr\["Name"\].ToString(); emp.Gender = rdr\["Gender"\].ToString(); emp.Email = rdr\["Email"\].ToString(); emp.Roles = rdr\["Roles"\].ToString(); }
hear I am passing rdr["ID"].ToString()..... line by line i want this to be executed in a single line is it posible Thanks Gopi Krishna
-
while (rdr.Read())
{
// emp = new EmployeeBll(rdr["ID"].ToString(), rdr["Name"].ToString(), rdr["Gender"].ToString(), rdr["Email"].ToString(), rdr["Roles"].ToString());emp.ID = rdr\["ID"\].ToString(); emp.Name = rdr\["Name"\].ToString(); emp.Gender = rdr\["Gender"\].ToString(); emp.Email = rdr\["Email"\].ToString(); emp.Roles = rdr\["Roles"\].ToString(); }
hear I am passing rdr["ID"].ToString()..... line by line i want this to be executed in a single line is it posible Thanks Gopi Krishna
If you have a constructor which accepts the property values, then your commented-out line will work. If you don't, an object initializer might help:
emp = new EmployeeBLL
{
ID = Convert.ToString(rdr["ID"]),
Name = Convert.ToString(rdr["Name"]),
Gender = Convert.ToString(rdr["Gender"]),
Email = Convert.ToString(rdr["Email"]),
Roles = Convert.ToString(rdr["Roles"]),
};You might also want to look at Dapper[^]:
using (var connection = new SqlConnection("..."))
{
List<EmployeeBLL> employees = connection.Query<EmployeeBLL>(
"SELECT ID, Name, Gender, Email, Roles FROM YourTable WHERE SomeCondition = @SomeParameter",
new { SomeParameter = "some value" })
.ToList();
...
}Or AutoMapper[^] with the AutoMapper.Data[^] extension:
using (var connection = new SqlConnection("..."))
using (var command = new SqlCommand("SELECT ID, Name, Gender, Email, Roles FROM YourTable WHERE SomeCondition = @SomeParameter", connection))
{
command.Parameters.AddWithValue("@SomeParameter", "some value");connection.Open(); using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection)) { if (reader.HasRows) { List<EmployeeBLL> employees = Mapper.DynamicMap<IDataReader, List<EmployeeBLL>>(reader); ... } }
}
(Code based on this StackOverflow answer[^].)
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer