Question

We have the following set of objects.

public class Form
{
    public int FormId { get; set; }
    public DateTime DateCreatedOn { get; set; }
    public string Status { get; set; }
}

// This is using TPT inheritance from Form
[Table("FormA")]
public class FormA : Form
{
    public string ExtraInfoA { get; set; }
    public virtual ICollection<Child> Children
}

// This is using TPT inheritance from Form
[Table("FormB")]
public class FormB : Form
{
    public string ExtraInfoB { get; set; }
    public virtual ICollection<Adult> Adults
}

public class Person
{
    public int PersonId { get; set; }
    public int FormId
    public DateTime DateOfBirth { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

// This is using TPH inheritance from Person
public class Adult : Person
{
    public int HowManyCars { get; set; }
    public string NationalInsuranceNo { get; set; }
    [ForeignKey("FormId")]
    public virtual FormB FormB { get; set; }
}

// This is using TPH inheritance from Person
public class Child : Person
{
    public int HowManyToys { get; set; }
    public string SchoolName { get; set; }
    [ForeignKey("FormId")]
    public virtual FormA FormA { get; set; }
}

This creates 3 tables for the forms Form, FormA, and FormB, all with the appropriate fields in them. It also creates 1 table for Person.

The problem is When we rely on the convention and don't specify the ForeignKey attribute the Person table contains 2 additional foreign key columns.

However when we do specify the ForeignKey attribute (as in the code above) we get the following error message.

`The foreign key component 'FormId' is not a declared property on type 'Child'. Verify that it has not been explicitly excluded from the model and that it is a valid primitive property.`

FormId is definitely a property of Child so I'm not sure what is going wrong.

Our real world situation is a lot more complicated that the situation above so I'd like to get it right now rather tham have multiple foreign keys.

Any help is very much appreciated.

Was it helpful?

Solution

You cannot define foreign key in the parent entity and navigation property in the child entity. They must both be defined in the same entity. What you are trying to do is even not valid in the database because you cannot have conditional foreign key constraint on the column - constraints to both FormA and FormB will be applied for every record and you will never be able to insert any record (because it would always violate constraint to FormA or FormB).

In short: You need either single navigation property in parent or separate foreign key for every child.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top