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

c# ef-core-2.1 entity-framework-core entity-framework-core-2.1

Question

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);
1
0
5/30/2019 6:19:33 AM

Accepted Answer

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);
1
5/30/2019 6:31:47 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow