Juan Jimenez
Juan Jimenez

Reputation: 5892

How should I map relationships between multiple inheritance models?

I have an Eentity Framework model with a Table Per Hierarchy (Brand) and also a Table Per Type (Vehicle) inheritance like this:

enter image description here

(Vehicle and Brand are abstract classes).

So far so good, I can access derived entities on linq queries using Vehicle.OfType<> or Brand.OfType<> method.

Now, Brand entity is one to many related with Vehicle on my conceptual model, So the question is, how should I make relationships on EF model so I can keep using navigation properties between Vehicle and Brand but at the same time keep the consistency of the TPH inheritance on Brand?, my first approach was to relate only derived clases, like:

enter image description here

But if I do this, I have no access to Brand directly from Vehicle, so I would have to do a double relation (between derived and base), like:

enter image description here

This works for me now, but I still have a duplicated relationship somehow, is this right?, do you have a better approach?, am I'm making some silly mistake on my modelling?

Upvotes: 3

Views: 425

Answers (1)

Sean Mickey
Sean Mickey

Reputation: 7716

It seems to me that the reason you are running into cross-linking in your model is because you are artificially separating Brand and Vehicle as top-level sibling entities. If you start with Brand, which seems essentially equivalent to Make, that becomes the true top-level entity. There is no need to separate Make for each vehicle type (car, motorcycle, truck, etc.); just introduce the entity Model between Make and Vehicle and I think that solves most of your cross-linking problems.

Then the relationships aren't strictly parent-child, but are more accurate as composition. So you have Make, which has a one-to-many composite relationship to Model, which in turn has a one-to-many composite relationship to Vehicle. Vehicles are instances of a Model, so there isn't really a parent-child relationship there either. With this structure, there is no need to branch the EF for each type of Vehicle, because that is just part of what is described by the Model entity.

I hope my answer is helpful and that I haven't missed any of the essential points of what you are trying to model-

Upvotes: 1

Related Questions