Matt Knowles
Matt Knowles

Reputation: 397

Entity Framework 6 Code First TPH Foreign Key in multiple derived classes

I'm trying to understand what I need to do in order to introduce the same Foreign Key in multiple derived classes when the Foreign Key is not present in the base class. The Foreign Key is to the same type, and I'm able to make the various derived classes all use the same column name, but when I try to introduce the Foreign Key annotation, Entity Framework 6 silently fails to create any Foreign Key at all.

It's worth mentioning that, if I allow EF to create Bar_Name1 instead of reusing the existing column, it adds the Foreign Key appropriately. But I come from a relational database background, and it offends my sensibilities to have multiple columns for the same thing.

I would prefer to be able to stick to using Annotations to mark up my code, but if this is something that can't be done with Annotations but can be done with the Fluent API, I'm willing to delve into that.

public class Foo
{
    [Key]
    public string Name { get; set; }
}

public class FooSub1 : Foo
{
    [Required, Column("Bar_Name")]
    public string Bar_Name { get; set; }

    [ForeignKey("Bar_Name")]
    public Bar Bar { get; set; }
}

public class FooSub2 : Foo
{
    [Required, Column("Bar_Name")]
    public string Bar_Name { get; set; }

    [ForeignKey("Bar_Name")]
    public Bar Bar { get; set; }
}

public class Bar
{
    [Key]
    public string Name { get; set; }
}

Upvotes: 2

Views: 875

Answers (1)

Moho
Moho

Reputation: 16543

The resolution to EF issue 1964 explains: "However, having an association in s-space here doesn't work anyway because it results in two database constraints which can only be satisfied if the dependent also matches the PK for the other relationship type. Such a match would usually only happen accidentally. The solution is to remove the associations from s-space like we do for similar TPC mappings." (emphasis mine)

EF drops the FK's on the merged column. In your case, the two FK's are logically the same, but EF doesn't know (or care about) that.

Upvotes: 2

Related Questions