Error: Unable to determine the principal end of an association between the types

You may get this error if you have entities related to itself. For example, you have a tree hierarchy.
The same entity may have references to its parent. In such case when you execute the query the error is appeared.The simplest class that can raise the exception.

C#

1

2

3

4

5

6

publicclassTreeItem

{

[Key]

publicintId{get;set;}

publicTreeItemRoot{get;set;}

}

If you try to query the entity and include the root you’ll catch the exception.

C#

1

vardata=TreeItems.Include(x=>x.Root).ToList();

In order to get rid of the exception you should change the entity as follows:

1

2

3

4

5

6

7

8

9

publicclassTreeItem

{

[Key]

[ForeignKey("Children")]

publicintId{get;set;}

[InverseProperty("Children")]

publicTreeItemRoot{get;set;}

publicICollectionChildren{get;set;}

}

This will help LINQ to find principal in the relationship and execute the query.