I have a MySQL database with tables for Items and for Stores, and a lookup table ItemStores, like this:
CREATE TABLE IF NOT EXISTS Items (
itemId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
description VARCHAR(256) NOT NULL DEFAULT '',
priceBeforeTax DECIMAL(10,2) NOT NULL,
) DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
CREATE TABLE IF NOT EXISTS Stores (
storeId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
storeName VARCHAR(128) NOT NULL,
) DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
CREATE TABLE IF NOT EXISTS ItemStores (
storeId INT NOT NULL REFERENCES Stores(storeId),
itemId INT NOT NULL REFERENCES Items(itemId),
quantity INT NOT NULL
) DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
The application stores the Items and Stores in ObservableCollectionss of Item and Store object, and some WPF controls are bound to these ObservableCollectionss, like so:
public class Store
{
public int storeId { get; set; }
public string storeName { get; set; }
public override string ToString()
{
return this.branchName;
}
}
private static ObservableCollection<Store> _stores = new ObservableCollection<Store>();
public static ObservableCollection<Store> Stores
{
get { return _stores; }
}
public class Item
{
public int itemId { get; set; }
public string description { get; set; }
public decimal priceBeforeTax { get; set; }
public override string ToString()
{
return this.description;
}
}
private static ObservableCollection<Item> _items = new ObservableCollection<Item>();
public static ObservableCollection<Item> Items
{
get { return _items; }
}
Now my dilemma centers on how to assign the ItemStores data. I am thinking about having a HashTable in each Item that maps storeID to the quantity of the item in each Store. Is there a better way to map it, assuming that I will be occasionally searching for an Item by its itemId? I’m already running a SELECT * FROM Items to populate the ObservableCollection, I fear that running another query to get the quantity from each store would really hammer MySQL. A JOIN won’t help as I do not know how many stores will be returned and returning multiple rows for the same item (one row for each store that carries it) will make it a pain to put the data into the ObservableCollection.
I would not take that road. You will soon find yourself building an ORM instead of using one. Furhermore, reading whole database into memory collections is bad idea because it will become performance problem once you realize that your data is stale and start reloading everything.
As for original question, ORM classes have collections of related children as properties, so you will not have to search for all of them – you will find a Store and read all ItemStore objects. If you need a list of an item in all stores, you will ask a database for that information.