How to remove circular reference from entity framework core

entity-framework-core json.net

Question

Web Api Core, Entity Framework Core

Situation - Many to many relationship. A, Join, B. Join has Id references to both A and B. A has collection for Joins. B has collection for Joins.

Goal - Get A with Joins with B - and no further.

Problem - I get A with Joins with B with the same singular Join back (in a collection). This is happening on the Entity Framework end. I believe EFCore is being clever and automatically putting that reference back in for me with the data it has. This would be nice, except I am returning this as Json to a client. The Json serialiser detects a circular reference and then omits it (by design). So my result is:

{ 
  // A stuff, 
  "joins": [{
    "B": {
      // B stuff, 
      "joins":[]
    }
  }]
}

I would like the empty joins collection to be null, so the Json serialiser drops it. Setting the collection to null doesn't work.

foreach (A a in query)
{
    foreach (Join join in a.Joins)
    {
        join.B.Joins = null;
    }
}

Although during the loop it appears to be setting the value to null, as soon as I escape it the references are back again.

Thank you for any and all help!

-- Note -- Later on I would like to be able to get B with Joins with A. So I cannot solve this by stopping all serialisation of Joins.A.

1
1
1/11/2018 2:48:31 PM

Popular Answer

I answered it by mistake while chasing another issue.

I was under the impression that enumerating the query forced the lazy load to run - since you can actually see data through it. When I forced my query into a ToList() everything worked as expected. I don't understand how a foreach doesn't throw an exception on an unloaded query, or why the visual studio debugger allows you to step through, seeing data, but then lazy loads the results of the query again later, but that's what seems to have happened.

I've been on this for two days, then one hour after finally posting online I solve it. Typical.

0
1/11/2018 3:52:39 PM


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