Neophear
Neophear

Reputation: 542

Best practice Objects from SQL

I tried searching but couldn't find a proper answer. I am creating an application that contains a lot of different objects. The data for these objects is saved in an MSSQL database. What is the best way to get data out?

For simplicity I will use two objects here: ItemObject UserObject

Both of them has a constructor which will get data from the Database:

public ItemObject(int ID) //same one for UserObject
{
    //Code to get the data from the database for this particular item
}

ItemObject has a property called CreatedBy which is a UserObject.

Now the question is what is the best way to create the ItemObject? I have two possible solutions:

Solution #1:

public ItemObject(int ID)
{
    DataTable dt = dal.GetDataTable("SELECT TOP 1 * FROM Items WHERE ID = @ID")
    this.CreatedBy = new UserObject((int)dt.rows[0]["UserID"])
}

Solution #2

public ItemObject(int ID)
{
    DataTable dt = dal.GetDataTable("SELECT TOP 1 * FROM Items INNER JOIN Users ON Items.CreatedBy = Users.ID WHERE Items.ID = @ID")
    this.CreatedBy = new UserObject((int)dt.rows[0]["UserID"], dt.rows[0]["Username"].ToString())
}

public UserObject(int ID, string Username)
{
    this.ID = ID;
    this.Username = Username;
}

In solution #1 I ask for data twice but in solution #2 I ask for data once. Although solution #1 is much "cleaner" and easier to read.

Edited after Steves correction.

Upvotes: 0

Views: 302

Answers (1)

Alex
Alex

Reputation: 106

I would go with solution two. From my point of view solution 1 is not acceptable, though it is "cleaner". And I think there is no best practice for reading to objects. I like much Entity Framework for this purpose.

Upvotes: 1

Related Questions