habib
habib

Reputation: 2446

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);

Upvotes: 1

Views: 2273

Answers (1)

Avin Kavish
Avin Kavish

Reputation: 8937

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);

Upvotes: 3

Related Questions