views:

188

answers:

3

Hi!

I have a database that has a one-to-one relationship modeled between a Person and a Address (that uses person id). However, I cannot find a way to make the map using NHibernate.

My table structure is the following:

PersonTable

PersonId
PersonName
PersonAge

AddressTable

PersonId
CountryName
StreetName
StateName

And I would like to have something like this as the final class:

PersonClass

int Id
string Name
int Age
Address HomeAddress

AddressClass

string Street
string Country
string State
Person Owner

I tried with HasOne relationship but I couldn´t reuse PersonId as Address Identifier.

Thanks!

Edit: I forgot to mention that I´m using FluentNHibernate so both fluent mapping and XML will be fine.

A: 

The problem is that your database schema does not represent a "Has One" relationship between Person and Address. It represents a "Has Many" relationship; You may be artificially limiting it to be one address per person, but that doesn't change the fact that the model is multiple addresses per person.

To get a "Has One" relationship, you would put the AddressID on the the PersonTable.

Chris Shaffer
You´re right! It is a "forced" HasOne. My real model is different than the one I used as example but since it´s related to a tax stuff in my country I thought I could explain it better with this simplifcation. Anyway, I still need to use the PersonId to get it´s address.
tucaz
If you can't change the database model to match what you want, then you could put a private property on the Person class that is a collection of Addresses, then expose a public property that returns the first element in the collection.
Chris Shaffer
That I got. My problem is that I don´t have an ID for the address. Addresses´s ID is the Person ID. How to use it?
tucaz
A: 

I did it using Id().GeneratedBy.Foreign() in Address class map referencing it to the Person´s ID and it worked.

Thanks!

tucaz
A: 

I would map it as a component of Person. In the person ClassMap add the following:

 Component(x => x.Address, m =>
        {
            m.Map(x => x.Street, "Street");
            m.Map(x => x.State, "State");
            // more here
        });

Cheers

Chev
Chev, the address is on another table. Not the same as the Person.
tucaz
I see that, being a 1 to 1 and the fact that it not referenced by any other entities and it is a value type - I would rather map it as a component gaining some perf and lose the additional join and schema. denormalised I know. just my 2c
Chev
I agree with you. The problem is that my database already exists and I cannot change it in order to both groups of information co-exists in the same table so I can use Component.
tucaz