Search code examples
databaseentity-frameworkef-code-first

Addresses database schema for multiple entities


I'm playing around with entity framework and code first approach. The scenario is this:

  • An user can have multiple companies (each company has an address)
  • An user can have multiple houses per company (each house has an address)

I'm thinking of two ways I can manage addresses:

  • Have an Address table with a column for CompanyId and HouseId (for companies addresses only CompanyId will be inserted and for houses both Ids will be inserted.
  • Have a CompanyAddress and HouseAddress tables with the only difference between them being the FK for CompanyId versus HouseId.

How would you do it? Is there any other, better options?


Solution

  • In EF Core you should use Owned Entity Types for this. In EF 6, use a Complex Type. Both allow you to have an Address type in .NET without having an Address table in your database.