2

I have a hierarchy of classes that is TPH in database. So we have a class Base, and children inheriting from it. Let's say they are ChildrenA, ChildrenB, ChildrenC.

The Base classes hierarchy have a conceptual relation to another classes hierarchy (also expressed in TPH in database) where the base class is RelatedBase, having children class RelatedChildrenA, RelatedChildrenB, RelatedChildrenC.

The conceptual relation is that :

  • ChildrenA could be related only to a RelatedChildrenA
  • ChildrenB could be related only to a RelatedChildrenB
  • ChildrenC could be related only to a RelatedChildrenC

I'm using entity framework fluent mapping with independent association MapKey method, to avoid exposing the foreign key id as a property.

So, basically, there is only one foreign key from a TPH hierarchy to another TPH hierarchy.

Given this foreign key is called RelatedId in database, I'm trying to express my fluent mapping as follow :

ModelBuilder.Entity<ChildrenA>().HasOptional(e => e.RelatedChildrenA)
 .WithOptionalDependent()
 .Map(a => a.MapKey("RelatedId"));

ModelBuilder.Entity<ChildrenB>().HasOptional(e => e.RelatedChildrenB)
  .WithOptionalDependent()
  .Map(a => a.MapKey("RelatedId"));

ModelBuilder.Entity<ChildrenC>().HasOptional(e => e.RelatedChildrenC)
  .WithOptionalDependent()
  .Map(a => a.MapKey("RelatedId"));

Unfortunately, this produce the following error :

One or more validation errors were detected during model generation: RelatedId: Name: Each property name in a type must be unique. Property name 'RelatedId' is already defined. RelatedId: Name: Each property name in a type must be unique. Property name 'RelatedId' is already defined.

Is this ever possible to map the same children property to the same base foreign key ?

Community
  • 1
  • 1
John-Philip
  • 3,392
  • 2
  • 23
  • 52
  • Ok, looks like it is not possible. See: - http://stackoverflow.com/questions/20744278/ef6-tph-foreign-key-mapping-in-derived-classes-using-base-class-property - http://stackoverflow.com/questions/11900155/how-to-map-foreign-keys-between-tph-tpt-objects-entity-framework-code-first – John-Philip Apr 20 '16 at 08:03

0 Answers0