I'm trying to port an existing application (using pure ADO.Net) to a new one using EF 4.3 Code First. It is worth mentioning that this is the first time I'm using EF.
Basically I have a suppliers table but with two specialization tables with attributes specific to each of the two types of suppliers.
Here is what the existing database looks like:
create table Supplier( id_supplier int not null identity --Bunch of other attributes ); create table Individual( id_individual int not null --not identity, gets the same value as the Supplier table --Attributes specific to individuals ); alter table Individual add constraint fk_individual_supplier foreign key(id_individual) references Supplier(id_supplier); create table Corporation( id_corporation int not null --not identity, gets the same value as the Supplier table --Attributes specific to corporations ); alter table Corporation add constraint fk_corporation_supplier foreign key(id_corporation) references Supplier(id_supplier);
So, as the tables show, a supplier can be either an individual or a corporation.
The existing application is like this:
- abstract class Supplier with its attributes
- class Individual deriving from Supplier with its additional attributes
- class Corporation deriving from Supplier with its additional attributes
The Ado.Net code currently works receiving Supplier objects, generating records on Individual table if the object passed is of Individual type or Corporation table if the object passed is of Corporation type.
So, every record on Supplier will have a matching one on either Individual or Corporation. Also, Individual and Corporation tables does not have foreign keys to any other table of the database. Instead, the relations are all with the Supplier table. The table generating the ID is Supplier.
How can I map this with Code First?
At first I thought about keeping my structure, I mean, Supplier abstract class and Individual and Corporation deriving from that. Because I need Entity to insert on Supplier table first (generate identity field), it seems that both Individual and Corporation model classes would be mapped to Supplier table.
But how would it be possible for it to receive the abstract class and insert on either one of the specialization tables depending on the type? I don't think this is possible without custom SQL which makes me think my approach is wrong.
Thanks in advance for helping.