2

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?

1
  • This is another perspective, but you can use JSON in this case. JSON is more fit for tree structures than table. Commented Aug 19, 2020 at 0:21

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.