The first blog post on this topic described how to create a domain model from an existing database and set inheritance relations between the generated classes. It was also shown how to use vertical mapping. In this post however, the focus is on the flat strategy (multiple classes mapped to one table) and forward mapping.

Let's add some new classes to the model from the previous post:

The new classes - Coupe and Limousine, will be mapped to the table of the Car class. To do that, select each of the new classes and change the "Mapped to" option in the Details Editor to 'Cars':

Since we are going to use flat mapping, a discriminator column in the table of the topmost class is required. Such column can be created manually using the "Add column" command in the Model Schema Explorer:

In the Table Editor dialog add an integer column and assign it an appropriate name like 'Discriminator':

Save the changes, select the Vehicle class in the diagram and open the Details Editor again. Set the newly created column as discriminator column and change the discriminator value to 1. It is required that the other classes have numeric discriminator values as well. Just go through each of them and assign a unique number for discriminator value:

Note that if you have existing records in the database, they will not have a discriminator value stored in the new column, so you have to either set such value for each record or drop the table data to avoid runtime errors.

The only step left is to update the database with the changes made so far to the model. To do so, rebuild the project and start the Update Database from Model wizard. On the first page choose the 'Generate and Execute Migration Update Script' option. Advance to page 2 and move all classes except Train to the 'Items to add' list. Going to the next page will create the needed script. In the preview pane you will notice that two new columns are added to the Cars table and one more (the discriminator) to the Vehicles table. Execute the script and finish the wizard. 

Now the model is complete and ready to be used:


using (TransportEntityDiagrams context = new TransportEntityDiagrams())
    Coupe coupe = new Coupe() { Seats = 2, MaxSpeed = 260, Color = "Blue", Price = 22000, Power = 321 };
    Limousine limo = new Limousine() { Seats = 4, MaxSpeed = 230, Color = "Black", Price = 90000, IsBulletProof = false };



Comments are disabled in preview mode.