0

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!

1 Answer 1

2

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; }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank's for your answer! I will try it tomorrow! I'll report about results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.