Search code examples
c#entity-frameworkef-code-first

Entity Framework Table Splitting: not in the same type hierarchy / do not have a valid one to one foreign key relationship


I'm using Entity Framework 6 with a Code-First approach, and I want two entities to be put in the same table. What am I doing wrong?

[Table("Review")]
public class Review
{
    public int Id { get; set; }
    public PictureInfo PictureInfo { get; set; }
    public int PictureInfoId { get; set; }
}

[Table("Review")]
public class PictureInfo
{
    [Key, ForeignKey("Review")]
    public int ReviewId { get; set; }
    public Review Review { get; set; }
}

The error I get: The entity types 'PictureInfo' and 'Review' cannot share table 'Review' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them.

What am I doing wrong?


Solution

  • Seems like the problem was that the relationship was interpreted as one-to-0..1 instead of one-to-one.

    The foreign key int PictureInfoId on the Review end was unneeded/ignored, so its non-nullability did not make the Review end of the relationship required. Removing this unneeded key and adding the [Required] attribute to the PictureInfo navigational property solved it.

    Here's the corrected Review class.

    [Table("Review")]
    public class Review
    {
        public int Id { get; set; }
        [Required]
        public PictureInfo PictureInfo { get; set; }
    }