views:

109

answers:

1

If you have a set of tables in the database that strictly consist of a string description and an ID, what is the best way to load these via NHibernate?

So suppose I have a Sandwich class, and a sandwich has a meat, a cheese, and a vegetable, where those three things are lookup tables in the DB. It seems to be the most conformant to NHibernate philosophy to have

public class Meat { string name; int id; }
public class Cheese { string name; int id; }
public class Vegetable { string name; int id; }
public class Sandwich { Meat meat; Cheese cheese; Vegetable vegetable; }

But with a few dozen tables like this in the database, classes seem to proliferate quickly. Suppose I set it up like this:

public class NameAndID { string name; int id; }
public class Sandwich { NameAndID meat; NameAndID cheese; NameAndID vegetable; }

Is this feasible? How would it be implemented in Fluent NHibernate?

+1  A: 

You'd need another column to determine the type. You could use an enum for that. Then all your lookups need to include that restriction....

CreateCriteria<NameAndID>.Add(Restrictions.Eq("ntype", E.Meat)

However, I'd prefer separate tables so you can have better foreign keys. Otherwise there is nothing in database constraints to stop you from making a sandwich that is simply 3 pieces of cheese.

dotjoe
I was actually thinking about keeping the separate tables and having them all map to NameAndID. Is that possible?
Ben Fulton
Kind of...just add empty class definitions that inherit from NameAndID. You'd still need to map each one though.
dotjoe