Search code examples
c#entity-framework-coreef-core-2.1entity-framework-core-2.1

Load related data without foreign key constraint in ef-core-2.1


I want to load related entities data Parent by using Eager Loading O/RM pattern. But I can't specify a foregin key constraint on ParentId because it creates a cycle which is not allowed. Currently, I'm using an inner join to load Parent data explicitly.

Here is my Domain Model that I'm using.

[Table("Category")]
public class CategoryDM
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    [Display(Name="Parent")]
    public int ParentId { get; set; }
    [NotMapped]
    public CategoryDM Parent { get; set; }
}

Is there any way to load related entities like this? or any other recommended way to achieve this.

var result = _context.Category.Include(e => e.Parent);

Solution

  • This should work fine, here is an exemplary working model.

    Model

        public class Category : ISelfRelated<Category>
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string ThumbnailUrl { get; set; }
            public int? ParentId { get; set; }
            public Category Parent { get; set; }
            public IEnumerable<Category> Children { get; set; }
        }
    

    Model configuration

                category.HasOne(c => c.Parent)
                    .WithMany(c => c.Children)
                    .HasForeignKey(c => c.ParentId)
                    .HasPrincipalKey(c => c.Id)
                    .OnDelete(DeleteBehavior.Restrict)
                    .IsRequired(false);