.net – Create object from database row


Let's say I'm building a data access layer for an application. Typically I have a class definition for a each kind of object that is stored in the database. Of course, the actual data access retrieves data in the form of a datareader, typed or untyped dataset, or similar, usually with the data needed to create one object per row in the results.

How would you go about creating your object instances in the data layer? Would have a constructor that accepts a datarow? If so, how would you make that type-safe? Or would you have your constructor list out one parameter for each field you want to instantiate, even if there could be many fields? Would you mark this constructor 'internal'?

Best Solution

I highly encourage you to use an ORM tool. Even simple projects can make use of ORM quickly and quietly... in particular, look at Castle's ActiveRecord tool (which sits on top of NHibernate to simplify model declaration).