currently I use DataSet to read data from ADO.NET SQL provider, but I read that DataReader is more efficient for some cases. Many a times I only read single/few records and don’t need in-memory data or multiple table relation manipulations.
-
Are there more clean and efficient ways to read ?
-
Can I in simple way map the full record directly to the Agent class, without having to parse out each column like I do now?
EDIT: – I have investigated somewhat on ORMs and used Linq2SQL a little, but the familiarity curve seems little steep, so left it at that. Please suggest other ways available within .NET and not any external tools.
public override Agent GetAgentByAgentId(string agentId)
{
Agent agent;
try
{
ArrayList paramList = new ArrayList();
paramList.Add(_dbUtilities.CreateSqlParamater("@agent_id", SqlDbType.VarChar, 10, ParameterDirection.Input, agentId));
// Query the database for an agent with given agentId
DataSet ds = _dbLib.ExecuteProcedureDS("sp_dbc_agentsSelect", paramList);
if (ds != null && ds.Tables != null && ds.Tables.Count > 0)
{
DataTable dt = ds.Tables[0];
if (dt.Rows.Count > 0)
{
agent = new Agent();
DataRow dr = dt.Rows[0];
// Get the agent data
agent.IsActive = bool.Parse(dr["is_active"].ToString());
agent.UserId = dr["user_id"].ToString();
....
}
}
First, I’d like to recommand SLak’s answer. This really is the answer to your question. I understand your trepidation about using large toolsets like EF, but it’s really the right solution and doesn’t have as much of a learning curve as you might think. There’s very little reason to go straight to things like a
DataReaderanymore. EF is part of .NET and I can’t encourage you enough to use it.Likewise, don’t go down the road of creating your own ORM of sorts with decorations and automatic code generation and the like. Do. Not. Do. It. In the end, you’ll spend as much time maintaining that as you do your business logic, and you’ll kick yourself for not using the work of many people who are a lot smarter than I am and probably you, as well 😉 (No offense, of course). If you’re looking for quick-and-dirty, then you need to go quick-and-dirty.
That being said, using a
DataReaderis the most lightweight method for reading data from the database.I’m not sure exactly how to answer your first question, other than to give you an example of using a
DataReaderin C#.The
whilestatement will execute for every row retrieved from the reader, though you can certainly short-circuit that loop if need be and not parse the entire result set.