Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create object from database row

Tags:

.net

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'?

like image 758
Joel Coehoorn Avatar asked Dec 10 '22 23:12

Joel Coehoorn


2 Answers

If you aren't content with DataRow or SqlDataReader, you should look at an ORM system like Linq to Sql or nHibernate, instead of re-inventing the wheel yourself.

(By the way, this is called the "ActiveRecord" pattern)

like image 144
Eric Z Beard Avatar answered Dec 28 '22 21:12

Eric Z Beard


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).

like image 26
Anthony Mastrean Avatar answered Dec 28 '22 23:12

Anthony Mastrean