473,386 Members | 2,129 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Advice for assigning data from a DataReader to object properties

Hi group

I am creating a web application that uses a simple DAL as an
ObjectDataSource.
To retrieve data from the database, I use a DataReader object from
which I then assign the various fields to properties in an object,
like so:

in the DB, the fields are defined as follows:
ProjectID int NOT NULL
Description varchar(50) NULL
Status int NULL
Active bit

My object looks like this:
public class Project
{
uint ProjectID;
string Description;
int Status;
bool Active;
}

Project p = new Project();
p.ProjectID = (uint) dr["ProjectID"];
p.Description = dr["Description"].ToString();
p.Status = (int) dr["Status"];
p.Active = (bool) dr["Active"];

I am experiencing a significant amount of problems when dealing with
nullable fields.
Because Description and Status are nullable, I have to check for that
prior to assigning it to the properties, otherwise an exception will
occur.

if (dr["Description"].ToString().Length 0) p.Description =
dr["Description"].ToString();
if (dr["Status"].ToString().Length 0) p.Status = (int) dr["Status"];
It seems to me that this is overly complex and very inefficient... Is
there a best practice that I'm missing to address these kind of
conversions and checks?

-- Hans

Jul 13 '07 #1
3 2189

Hi,

I hope you get the idea.

Private Sub Form1_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load

Dim SelectStatement As String ' 2.
The SelectStatement Used for SQL
Dim NorthwindDataReader As SqlDataReader ' 3.
The Datareader that will return from the DataAccess Object
Dim Con As String =
System.Configuration.ConfigurationManager.AppSetti ngs("Northwind")
SelectStatement = "Select * From AccountsTable"

'Instantiate the Data Access Oject
Dim localSQLServer As New DataServer(Con)
'Call the runSQLDataSet Function that takes the SQL String, an
optional Table name and returns the DataSet
NorthwindDataReader =
localSQLServer.runSQLDataReader(SelectStatement)
'We can now populate the Grid with the returning DataSet's
DataTable
'DataGridView1.DataSource = NorthwindDataReader
'DataGridView1.DataBindings()

If NorthwindDataReader.Read = True Then

TextBox1.Text = NorthwindDataReader(0)
TextBox2.Text = NorthwindDataReader(1)
End If

Dim intCol As Integer
With NorthwindDataReader
If .HasRows Then
DataGridView1.Rows.Clear()
'Add column definition: FieldName, and ColumnName
For intCol = 0 To .FieldCount - 1
DataGridView1.Columns.Add(.GetName(intCol),
GetName(intCol))
Next
'Base column width on header text width
DataGridView1.AutoSizeColumnsMode = _
DataGridViewAutoSizeColumnsMode.ColumnHeader
While .Read
'Get row data as an Object array
Dim objCells(intCol) As Object
GetValues(objCells)
'Add an entire row at a time
DataGridView1.Rows.Add(objCells)
End While
End If
End With
End Sub

--
bhar
------------------------------------------------------------------------
Posted via http://www.codecomments.com
------------------------------------------------------------------------

Jul 13 '07 #2
the main problem is value types cannot be null. use the new nullable
type. then check for DBNull being returned.

public class Project
{
uint? ProjectID;
string Description;
int? Status;
bool? Active;
}

p.ProjectID = dr.IsDBull(dr.GetOrdinal("ProjectID") : null ? (uint)
dr["ProjectID"];
i'd write a helper routine

-- bruce (sqlwork.com)

Froefel wrote:
Hi group

I am creating a web application that uses a simple DAL as an
ObjectDataSource.
To retrieve data from the database, I use a DataReader object from
which I then assign the various fields to properties in an object,
like so:

in the DB, the fields are defined as follows:
ProjectID int NOT NULL
Description varchar(50) NULL
Status int NULL
Active bit

My object looks like this:
public class Project
{
uint ProjectID;
string Description;
int Status;
bool Active;
}

Project p = new Project();
p.ProjectID = (uint) dr["ProjectID"];
p.Description = dr["Description"].ToString();
p.Status = (int) dr["Status"];
p.Active = (bool) dr["Active"];

I am experiencing a significant amount of problems when dealing with
nullable fields.
Because Description and Status are nullable, I have to check for that
prior to assigning it to the properties, otherwise an exception will
occur.

if (dr["Description"].ToString().Length 0) p.Description =
dr["Description"].ToString();
if (dr["Status"].ToString().Length 0) p.Status = (int) dr["Status"];
It seems to me that this is overly complex and very inefficient... Is
there a best practice that I'm missing to address these kind of
conversions and checks?

-- Hans
Jul 13 '07 #3
Hi Bruce,

I was hoping there was another way, but if the nullable data types are
what you're proposing, then that's what I'll go for.

I do have some more questions about it though... I think the answers
will very depending on whom I'm talking to, but that's just what I'm
after, so I can get an initial repository of paths to follow.

1. When using nullable types, would you recommend a best practice to
use nullable types only for the private fields inside the object
(those that get their data from the DB), and work with standard types
for the public properties?
For example:
private int? _status
public int Status
{
get
{
if (_status != DBNull)
return _status;
else
// return some default value
}
set
{
_status = value;
}
}

public void GetData()
{
//get DataReader object -- code omitted --
_status = (int?) dr["Status"];
}

2. what's your take on allowing NULL in the database? Thus far I've
always allowed it for fields that could be empty. But for fields that,
if empty, should take a default value, would it be better to set that
default value in the DB and set the field as NOT NULL. Or is it better
to provide the default value in the property set of the object class
(like in the example above)? I know there's no definitive answer to
this, but I'm looking for reasonings for and against nullable DB
fields.

-- Hans

On Jul 13, 6:00 pm, bruce barker <nos...@nospam.comwrote:
the main problem is value types cannot be null. use the new nullable
type. then check for DBNull being returned.

public class Project
{
uint? ProjectID;
string Description;
int? Status;
bool? Active;
}

p.ProjectID = dr.IsDBull(dr.GetOrdinal("ProjectID") : null ? (uint)
dr["ProjectID"];

i'd write a helper routine

-- bruce (sqlwork.com)

Froefel wrote:
Hi group
I am creating a web application that uses a simple DAL as an
ObjectDataSource.
To retrieve data from the database, I use a DataReader object from
which I then assign the various fields to properties in an object,
like so:
in the DB, the fields are defined as follows:
ProjectID int NOT NULL
Description varchar(50) NULL
Status int NULL
Active bit
My object looks like this:
public class Project
{
uint ProjectID;
string Description;
int Status;
bool Active;
}
Project p = new Project();
p.ProjectID = (uint) dr["ProjectID"];
p.Description = dr["Description"].ToString();
p.Status = (int) dr["Status"];
p.Active = (bool) dr["Active"];
I am experiencing a significant amount of problems when dealing with
nullable fields.
Because Description and Status are nullable, I have to check for that
prior to assigning it to the properties, otherwise an exception will
occur.
if (dr["Description"].ToString().Length 0) p.Description =
dr["Description"].ToString();
if (dr["Status"].ToString().Length 0) p.Status = (int) dr["Status"];
It seems to me that this is overly complex and very inefficient... Is
there a best practice that I'm missing to address these kind of
conversions and checks?
-- Hans

Jul 17 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: vanGogh | last post by:
I have generated classes based on an Xml schema file (xsd) using the XSD.exe tool. My goal is to: - write an application that can parse XML documents - fill objects (based on the generated...
2
by: Andrew | last post by:
I am starting my first C# project and have a design issue which I would appreciate some advice about. I am wondering whether to use dataset to pass information between components or if I should...
2
by: Josema | last post by:
Hi to all. I have a DataReader that its associated with a connection. My query has results, and i have a class with the same fields name than the table in the database... I would like to...
1
by: mhnazly | last post by:
i'm trying to read data from SQL Server database using data reader and assigned it to a label in my asp.net web application. but when the button is clicked, nothing appears. please help, thanks. ...
1
by: Sachin Kuchinad | last post by:
Hi All I am using .NET Framework version 1.0.3705 to build a website. Now i have made a webform and on that i have added a dropdown to the page I bind this listbox to a datareader . This does...
13
by: Alan Silver | last post by:
Hello, MSDN (amongst other places) is full of helpful advice on ways to do data access, but they all seem geared to wards enterprise applications. Maybe I'm in a minority, but I don't have those...
53
by: Hexman | last post by:
Hello All, I'd like your comments on the code below. The sub does exactly what I want it to do but I don't feel that it is solid as all. It seems like I'm using some VB6 code, .Net2003 code,...
232
by: robert maas, see http://tinyurl.com/uh3t | last post by:
I'm working on examples of programming in several languages, all (except PHP) running under CGI so that I can show both the source files and the actually running of the examples online. The first...
1
by: Sh0eshineboy | last post by:
System.Data.SqlClient.SqlException: Divide by zero error encountered System.Data.SqlClient.SqlDataReader.Read() +176 System.Data.Common.DbDataAdapter.FillLoadDataRow(SchemaMapping mapping)...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.