0

I'm trying to set up a many-to-many relationship on ef core following this model: https://stackoverflow.com/a/46184785/11234800

But every time I try to query a person with all its clubs from this relationship, as follows:

    public async Task<IList<Person>> GetAll()
    {
        var query = _dbContext.Set<Person>()
            .Include(pc => pc.PersonClubs).ThenInclude(c => c.Club)
            .AsQueryable();

        return await query.ToListAsync();
    }

I end up running in a self-referencing loop error, which I solved by doing this: https://stackoverflow.com/a/34847316/11234800

Is it really necessary to ignore this type of error or there's a better way to solving this issue?

Rogerio Schmitt
  • 1,055
  • 1
  • 15
  • 35

1 Answers1

2

IMO the self-referencing loop issue is only a result from a poor design choice in your application.

I would recommend you not to return the entity which is connected to EF and instead return a model which represents the application endpoint interface, a data transfer object. That object will only present the necessary data, which should be presented from that specific endpoint.

For example, if you return the Person entity as you do, is the relation property PersonClubsId really needed to represent a person? Or for instance, if you have some metadata field like CreatedDate, CreatedBy. Those should most likely not be included. Instead create your own class which will represent a Person with the properties that represents your entity in the best way.

Another reason why you should decouple the EF entity from your application endpoint interface is because if you make any changes in the db-structure for your Person entity, those changes will be reflected upon the client as they both uses the same model.

Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69
  • 1
    The first time I read your response I thought it was silly. Then I went to check my code and I saw my endpoint was indeed trying to return an entity instead of its respective DTO. As soon as I corrected it my code started to work just fine, thanks a lot! – Rogerio Schmitt Dec 27 '19 at 16:20