views:

47

answers:

1

I'm hoping someone can help me with mapping a legacy database. The problem I'm describing here has plagued others, yet I was unable to find a real good solution around the web.

DISCLAIMER: this is a legacy DB. I have no control over the composite keys. They suck and can't be changed no matter much you tell me they suck. I can't add surrogate keys either. Please don't suggest either of these as they are not options.

I have 2 tables, both with composite keys. One of the keys from one table is used as part of the key to get a collection from the other table. In short, the keys don't fully match between the table. ClassB is used everywhere I would like to avoid adding properties for the sake of this mapping if possible.

public class ClassA
{
    //[PK]
    public string SsoUid;

    //[PK]
    public string PolicyNumber;

    public IList<ClassB> Others;

    //more properties....

}

public class ClassB
{
    //[PK]
    public string PolicyNumber;

    //[PK]
    public string PolicyDateTime;

    //more properties
}

I want to get an instance of ClassA and get all ClassB rows that match PolicyNumber. I am trying to get something going with a one-to-many, but I realize that this may technically be a many-to-many that I am just treating as one-to-many.

I've tried using an association class but didn't get far enough to see if it works. I'm new to these more complex mappings and am looking for advice. I'm open to pretty much any ideas.

Thanks, Corey

A: 

The easiest way to handle mapping legacy database schemas is to add a surrogate generated primary key (i.e. identity in SQL Server) to each database table and change your existing composite primary keys to unique constraints. This allows you to keep your existing foreign keys and makes the NHibernate mapping easy.

If that's not possible then you may be able to use property-ref in your mappings to accomplish this.

Edit: You can always fall back to an anemic domain model. That is, map each class but exclude the relationships. You would have one data access method to get ClassA by key, and one to get a collection of ClassB by PolicyNumber.

Jamie Ide
No matter how hard I try on my posts regarding composite keys, I just can't get people to quit suggesting I change the DB. I realize that I didn't say I can't add keys, which was an oversight, but I can't change the DB. I've been fighting that battle for a long time.DISCLAIMER: this is a legacy DB. I have no control over the composite keys. They suck and can't be changed no matter much you tell me they suck. I can't add surrogate keys either.
Corey Coogan
I saw this "I'm open to pretty much any ideas" but missed "I can't add surrogate keys either". I have one more idea that I'll add with an edit.
Jamie Ide
I actually added the part about surrogate keys after your comment. I know I left that part out. Thanks for the ideas.
Corey Coogan