Niyazi Ekinci
Niyazi Ekinci

Reputation: 87

Entity Framework Core Recursively Include Problem

I have an entity that is including a list. And every list item has a reference to my entity.

public class Pack
{
   public Guid Id {get; set;}
   public string Name {get; set;}
   public List<Media> Medias {get; set;}
}

public class Media
{
   public Guid Id {get; set;}
   public string Name {get; set;}
   public Guid PackId {get; set;}
   public Pack Pack {get; set;}
}

As you can see, it's a classical one-to-many relationship. I wanna fetch Packs from the database including Medias, therefore i wrote this code:

public List<Pack> GetPacks(){
   return _dbContext.Pack.Where(x=>x.IsActive == true).Include(x=>x.Medias).ToList();
}

When I get Packs with it's Medias included, I have a problem with recursively joining. I am getting Packs with Medias but every Media again has a reference to the Pack. The result looks like below:

{ //pack
   Name: ...
   Medias: [{Id: ..., Pack: {Name: ... Medias: [{.. Pack: { ... Medias...
}

In short, When I include Medias while selecting a Pack, I am getting a recursively referencing problem.

What is the reason of this?

Upvotes: 2

Views: 392

Answers (1)

Carlos
Carlos

Reputation: 114

Add [JsonIgnore] above the Pack Property in your Media class.

[JsonIgnore]
public Pack Pack { get; set; }

When using your query the result will be

[{
    "id":"555d42a1-914e-4976-119b-08d84400ba5a",
    "name":"My Package",
    "medias":
    [{
        "id":"db406c89-ea4b-4e55-6621-08d84400ba50",
        "name":"New Media",
        "packId":"555d42a1-914e-4976-119b-08d84400ba5a"
    }]
}]

So you only have the PackId included and not the whole Pack.

Upvotes: 1

Related Questions