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.
public class TreeItem { [Key] public int Id { get; set; } public TreeItem Root { get; set; } }
If you try to query the entity and include the root you’ll catch the exception.
var data = TreeItems.Include(x => x.Root).ToList();
In order to get rid of the exception you should change the entity as follows:
public class TreeItem { [Key] [ForeignKey("Children")] public int Id { get; set; } [InverseProperty("Children")] public TreeItem Root { get; set; } public ICollection Children { get; set; } }
This will help LINQ to find principal in the relationship and execute the query.