Okay, this is an issue I ran into the other day, which, coincedentally, somebody else did on the
http://asp.net forums. They articulated the problem perfectly, so I'll post their post here:
Quote:
The 2nd thing that I found a bit constricting is when you have a database table that looks like this:
car_id, bigint
car_name, varchar(100)
manufacturer_id, bigint --foreign key reference to another table
and a matching class that looks like this:
public class Car
{
private int _id;
public int ID
{
get { return _id; }
set { _id = value; } //you'll see why I have a setter in a minute
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private Manufacturer _mfg;
public Manufacturer Manufacturer
{
get { return _mfg; }
set { _mfg = value; }
}
//more properties and methods below
}
Okay, simple enough. Now the difference you see here is that the database has a single integer value for the reference to the other table (manufacturers). The class has an actual object, not just a manufacturer_id. Now picture we are on a form creating a new car, and we have a dropdown list of manufacturers (which, btw, in my NHibernate framework is as easy as:
dropdown.DataSource = Manufacturer.GetAll();
). Okay, so the user types in a name and selects a manufacturer from the list, and then clicks a button to save it:
private void btnSaveCar_Click(object sender, EventArgs e)
{
Car car = new Car();
car.Name = txtName.Text;
car.Manufacturer = //what do we put here? we have 2 choices
//we can get the entire object from the database (wast of a call)
car.Manufacturer = Manufacturer.Get( ddlManufacturers.SelectedValue );
//or we can create a dummy object
Manufacturer mfg = new Manufacturer();
mfg.ID = ddlManufacturers.SelectedValue; //fool our object by just providing the id
//finally, save the object
car.Save();
}
Now, the 2nd method I don't like at all, for 1 because there is no reason to ever SET the ID field, and 2, we are dealing with a fake object. If we make further changes to the car the updates could ripple down to the child objects (and may cause undesired results). So I have stuck with method 1, using Get and wasting a call to the database, with the advantage that I am working with a true object.
Anyway, I have yet to do any really complex querying, and that's really the part I am dreading, but other than that I have saved tons of time by not writing any SQL at all.
I also resorted to method 1 (the wasted database call) because it was the "cleanest". How are others handling this common scenario? Dummy objects just feels... wrong.