I agree with Dan. You won't get any noticeable benefit from only retrieving some columns from a single row. However, in some cases you may have just an ID and a single field that you want to update. If there is no other reason to instantiate the object, you might want to write a method to update just that field. For example, an UpdateFirstName(int userId, string newUsername) method (one DB call!) that precludes the need to retrieve the row and then update it (two DB calls!). That is obviously not object oriented, but if the efficiency is worth it you might decide to bend the rules.
A couple of other points -
1. If you know that you know the type of a field coming from the DB, you can safely cast the DataRow column. See example 1 below.
2. Consider using the new (.net 3.0, I think?) object initializer syntax. See example 2 below. It looks more elegant IMO and you don't have to write a new constructor for every variation of input parameters.
Sean Brown, Sep 30, 2010
You can use wrapper class around DataRow and select and update all fields.
Example UserData is wrapper class and User business class extends UserData class.
Kaupo Nava, Sep 29, 2010
This is the modern approach to writing SQL: you only access entire rows in a table. In other words, you don't just SELECT two columns and UPDATE perhaps one (if only one was changed by the user). You look at the row as a unit of work, i.e. business object.
Clearly, this causes redundancy. For example, in a screen in which someone updates a User, rarely all columns are changed, but you do SELECT and UPDATE all columns in each transaction.
However, the advantage of doing this is it greatly simplifies your code because all you need is one SELECT, one UPDATE, and one DELETE method and with these you fundamentally cover all scenarios. (in reality you may have a few more methods, but not many, look at the Reposity pattern for examples of this).
Hope this helps.
Dan McMillan, Sep 24, 2010
Oct 11, 2010
Thanks Rajesh.. I got the concept...
Aug 08, 2010