We have a MySQL database with employees, companies and addresses tables.
The setup works like this: employees and companies each have an id. Since they are in two different tables, an employee can have id = 1 and the company can have id = 1. Both can have multiple addresses.
Now the address table has two columns that links it either to a company or to a employee:
element_id
element_type_id
element_type_id is either 1 = person or 2 = company
The whole thing is a bit more complex and there are many more tables, but that kinda explains the concept.
The problem is now that we would like to start using the Entity Framework and for that we need to define relationships with foreign keys.
But that sounds pretty much impossible with the setup that we currently have, does it?
Since the address table would need to be combined with the person and the company somewhow….
Any ideas?
This concept is known as polymorphic associations. I once asked a question about it, because I had a similar data structure that I wanted to make referentially sound. In terms of this question your
Addresscorresponds with the Comment table andEmployeeandCompanywith Person etc.The answer was excellent. If you can change the schema I would certainly go for it and use that approach.
If you can’t change the schema you can always subtype your
Addressclass in your EF model and useelement_type_idas the discriminator column. You would create subtypesEmployeeAddressandCompanyAddress, whereEmployeerefers to the former andCompanyto the latter. But as “the whole thing is a bit more complex” I’m not sure if this will be feasible in your situation.