1
votes

I have a group of objects that share some similar properties, so they inherit these from a base class. Here is a simple example of what I am doing.

I have 2 objects, Employee and Customer that have corresponding tables. Each contain a list of addresses. The Address class is shared between the two objects, but reside in two seperate tables EmployeeAddress and CustomerAddress.

EmployeeAddress - EmployeeId uniqueidentifier
                  Address varchar (50)
                  ZipCode varchar (10)
                  City varchar (20)
                  State id NOT NULL

CustomerAddress - CustomerId uniqueidentifier
                  Address varchar (50)
                  ZipCode varchar (10)
                  City varchar (20)
                  State id NOT NULL          

How can I map my Address object to two seperate tables? I want it to be able to pull data from either the EmployeeAddress or CustomerAddress table when it needs to.

I have tried:

(EmployeeMap)
HasMany(x => x.Addresses).Table("EmployeeAddress").KeyColumn("EmployeeId");

But nHibernate complained that the Address class did not have its own mapping class.

(AddressMap)
Id(x => x.Id);
Map(x => x.ParentItemId);  //generic way to reference EmployeeId or CustomerId
                           // but I can't specify which column name it should 
                           //  actually be using

But nHIbernate tried grabbing data out of an Address table which doesn't exist, and my column names were wrong.

FYI: I will not be able to combine the two Address tables into one.

1

1 Answers

0
votes

You can create mappings that inherit from each other

Base mapping class that contains all the duplicated values:

public class AddressBaseMap<T> : ClassMap<T> where T : Address
{
    public AddressBaseMap()
    {
        Map(x => x.Address);
        //etc
    }
}


public class CustomerAddressMap : AddressBaseMap<CustomerAddress>
{
    public CustomerAddressMap()
    {
        Table("CustomerAddress");
    }
}

I would also suggest the use of Components so that you can encapsulate all of the fields into a single class.