0

Following is a csharp code which set database data to an object. It set each of the variables needed.

objClsProfileMaintenance.Name = Convert.ToString(dtProfileInfo.Tables[0].Rows[0]["Name"]);
objClsProfileMaintenance.Email = Convert.ToString(dtProfileInfo.Tables[0].Rows[0]["Email"]);
objClsProfileMaintenance.ContactNo = Convert.ToString(dtProfileInfo.Tables[0].Rows[0]["ContactNo"]);
objClsProfileMaintenance.HPNo = Convert.ToString(dtProfileInfo.Tables[0].Rows[0]["HPNo"]);
objClsProfileMaintenance.Remark = Convert.ToString(dtProfileInfo.Tables[0].Rows[0]["Remark"]);
objClsProfileMaintenance.Termination_Dt = Convert.ToString(dtProfileInfo.Tables[0].Rows[0]["Termination_Dt"]);
objClsProfileMaintenance.Reason = Convert.ToString(dtProfileInfo.Tables[0].Rows[0]["Reason"]);
objClsProfileMaintenance.PersonInCharge = Convert.ToString(dtProfileInfo.Tables[0].Rows[0]["PersonInCharge"]);
objClsProfileMaintenance.Address1 = Convert.ToString(dtProfileInfo.Tables[0].Rows[0]["Address1"]);
objClsProfileMaintenance.Address2 = Convert.ToString(dtProfileInfo.Tables[0].Rows[0]["Address2"]);
objClsProfileMaintenance.Address3 = Convert.ToString(dtProfileInfo.Tables[0].Rows[0]["Address3"]);
objClsProfileMaintenance.Address4 = Convert.ToString(dtProfileInfo.Tables[0].Rows[0]["Address4"]);

I just wondering, is there have any better/easy way to retrieve database data into an object?

Thanks.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
henryloke
  • 67
  • 5

2 Answers2

2

I just wondering, is there have any better/easy way to retrieve database data into an object?

Yes.

  • Reading from a DbDataReader (e.g. SqlDataReader) directly instead of via a DataTable and DbDataAdapter.
  • Use an ORM:
    • Entity Framework is .NET's first-party ORM.
    • Dapper
    • NHibernate.
    • I'm sure there are others.
Dai
  • 141,631
  • 28
  • 261
  • 374
1

Definitely yes, even if you used plain ADO.NET. You can use a full featured ORM like Entity Framework or a micro-ORM like Dapper that just maps the results to objects by name.

Using Dapper, you'd only have to write a single line, eg :

var sql=@"Select Name,Email... 
from someTable
where customerId=@customer";

var results=connection.Query<Maintenance>(sql,new{customer=123});

Dapper will create and execute a parameterized query using the supplied property names as parameter names, and map the results to object properties by name, taking care of any conversions.

Dapper can also execute queries asynchronously:

var results=await connection.QueryAsync<Maintenance>(sql,new{customer=123});
Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236