Tien Do
Tien Do

Reputation: 11069

How to use look up values with NHibernate?

How do you handle look up values with NHibernate? For example, I have an Order entity and it has a BillingAddress property that is a value object named Address, it's simple if the Address object just contains State and Country properties as strings. But what if I want a Country contains a list of its states the Order form can populate appropriate state dropdown list for each selected country.

Can I still create Country and State as value objects? Or they must be entities? And if they are entities, can Address be a value object?

Below is a sample code of my example:

public class Order
{
  public virtual int OrderId { get; set; }
  public virtual Address BillingAddress { get; set; }
}

public class Address
{
  public virtual State State { get; set; }
  public virtual Country Country { get; set; }
}

public class Country
{
  public virtual string Name { get; set; }
  public virtual ICollection<State> States { get; set; }
}

public class State
{
  public virtual string Name { get; set; }
  public virtual Country Country { get; set; }
}

Upvotes: 2

Views: 219

Answers (1)

Jon Adams
Jon Adams

Reputation: 25137

If you want to store the lookup data in the database, then they need to be entities. Otherwise, it is up to you. If you do, I suggest marking them as immutable and putting them in a read only 2nd-layer cache.

If you store them as values, and they have multiple fields like Abbrevation, Name, Coordinates, etc. then you can save the id as a value in the data store, and have the lookup data hard-coded as a plain C# class. You'll just retrieve the id value from NHibernate, and then your calling code will have to run the lookup methods on the class. Not as elegant, but simplifies from the NHibernate/database perspective.

Either method is acceptable--it more depends on how you plan on using them: who is maintaining and using the code at each level, where you want the caching and/or lookup code, if you control the calling code or not, etc.

Upvotes: 1

Related Questions