Oleg
Oleg

Reputation: 1775

Error in LINQ (column doesn't exist) when using Entity Framework

This question is generalization of my previous question:

Error in LINQ when work with PostGreSQL by Entity Framework
I have hypothesis, that, If between 2 tables exist more than 1 relation (7 for my example), EF try to normalize this table by adding additional column.

For example model a:

public partial class a
{        
    [Key]
    public int id { get; set; }

    [ForeignKey("contractors"), Column(Order = 0)]
    public Nullable<int> ot_contractor_id { get; set; }

    [ForeignKey("contractors1"), Column(Order = 1)]
    public Nullable<int> gvo_contractor_id { get; set; }

    public virtual contractors contractors { get; set; }
    public virtual contractors contractors1 { get; set; }    
}

Table [a] have relations to table [contractors].[id] So, EF generate column's "contractors_id" and "contractors1_id".

Other tables have only 1 relation and they work normal!

The question: Is that hypothesis correct?! And the problem of excess column comes from unnormal tables with a few relations? Thanks!

Upvotes: 0

Views: 1666

Answers (1)

Slauma
Slauma

Reputation: 177163

It can happen if you have inverse navigation properties in contractors class, like so:

public partial class contractors
{
    //...

    public virtual ICollection<a> aCollection { get; set; }
    public virtual ICollection<a> aCollection1 { get; set; }
}

In this case EF won't know which one belongs to which navigation property in class a and assume four relationships instead of two (or three instead of two if you have only one collection). Those additional relationships will have a separate foreign key and one of them is contractors_id. If that doesn't exist in the database you get an exception.

You can fix the problem by applying the InverseProperty attribute in class a:

[InverseProperty("aCollection")]
public virtual contractors contractors { get; set; }
[InverseProperty("aCollection1")]
public virtual contractors contractors1 { get; set; }

Upvotes: 2

Related Questions