views:

59

answers:

1

I have the following database tables. Primary keys are ID and AnimalType.Type is a unique string.

Animal
- ID
- Name
- TypeID

AnimalType
- ID 
- Type [Herbivore, Carnivore]

My classes are as follows.

public class Animal
{
    public int ID { get; private set; }

    public string Name { get; set; }

    public AnimalType Type { get; set; }
}

public class AnimalType
{
    private int ID { get; set; }

    public string Type { get; set; }
}

How would I get the following code to work in NHibernate so that it references the same AnimalType of Herbivore?

var horse = new Animal() { Name = "Horse", Type = new AnimalType() { "Herbivore" }};

repository.SaveOrUpdate(horse);

var rabbit = new Animal() { Name = "Rabbit", Type = new AnimalType() { "Herbivore" } };

repository.SaveOrUpdate(rabbit);

UPDATE

Be nice if I could get NHibernate to perform this logic: http://andreas.scherbaum.la/blog/archives/11-Avoid-Unique-Key-violation.html

+1  A: 

I'd investigate a few options.

1) If the data doesn't change frequently, can you make AnimalType an Enum instead of an Entity Object?

2) Instantiate an object of the Herbivore AnimalType using animalTypeRepository.FindByType("Herbivore") and pass that object into your new Animal.

3) Move the above logic into the animalRepository.SaveOrUpdate(animal) method so that you'd have...

public class AnimalRepository
{
  public void SaveOrUpdate(Animal animal)
  {
    var animalType = animal.Type;
    if (animalType.ID == 0)
    {
      animal.Type = animalTypeRepository.Find(animalType.Type);
    }

    // save or update animal...
  }
}
Kevin Swiber
This is the way I assumed it would be done, my question specifically is around support within NHibernate for this scenario.
bleevo
You could investigate the usage of the property-ref attribute on the many-to-one tag within the Animal mapping. This allows you to reference another table by a non-FK column. Although if the data isn't going to change, then you are far better to use an enum.
Nigel