CodeMaster2008
CodeMaster2008

Reputation: 921

EF 4.1 Code First - mapping relationship

I'm starting with EF 4.1 code first and I was wondering if somebody out there can help me understand the best way to map this scenario:

I have a class Address:

public class Address
{
     public int Id { get; set; }
     public string Line1 { get; set; }
     public string Line2 { get; set; }
     public string City { get; set; }
     public string State { get; set; }
     public string ZipCode { get; set; }
}

And I have two other classes who has addresses:

    A) Company has Office Address (required) and Mailing Address
    A) Person has Home Address (required), Work Address and "Other Address"

The same scenario also happens with phone numbers. I really appreciate any help on this. Thanks in advance.

Upvotes: 1

Views: 134

Answers (1)

StuartLC
StuartLC

Reputation: 107237

I would definitely avoid the "Table per Hierarchy" kind of modelling (i.e. where you embed address directly into Company and Person)

Meaning Addresses are normalised out of your entities and stored separately (so TPC)

You could then either

  1. Add a FK "OfficeAddressId" (non nullable) and "MailingAddressId" (nullable) to Company and 3 x Address FK's in Person However, depending on your requirements for 'address querying', because there are two different entities referencing Addresses, it isn't very easy to figure out which address belongs to which entity or which type of address you are looking at, without having to 'blindly' join back into both Company and Person.

OR possibly overkill, but an even more flexible model would be

  1. Add a many : many table "EntityAddress" linking either Company to Address or Person to Address, and then add classification table "AddressType" (Office, Mailing, Home, Work etc). Although you would need to constrain the types of address added to this many:many through business logic, it allows the most flexibility for future extension of addresses.

Have a look at these posts here and here for other ideas on how address problems have been tackled.

Upvotes: 1

Related Questions