0
votes

When using the mapping-by-code/conformist approach in NHibernate, how can I create a class mapping so that Person.CountryId is created as a Foreign Key to my Country entity?

When loading the Person entity, I do not want to use the Country entity directly in the person entity (since they are different aggregate roots) but only reference it by ID and still have the FK relation defined in the database.

public class Person : Entity, IEntity
{
    public Guid CountryId { get; protected set; }
}

public class Country : Entity, IEntity
{
    public string Name { get; protected set; }
}
1

1 Answers

0
votes

It is fine if an aggregate root has a reference to an other aggregate root. The idea is that you are not allowed to reference to parts of other aggregates.

What you want to do is not easily possible. Someone needs to know which Guid to put into CountryId-column. If your application can't answer that question, nobody can.

What you might try is to have a class that will contain the mapping between the country and the person:

public class CountryToPersonMapping
{
    public Guid Find(Person entity)
    {
    }

    public void AddMapping(Person person, Country country)
    {
    }
}

and then find a way to pass the instance of this class to a custom type in NHibernate to set the correct column. Probably using a service locator.