0

I am using ASP.NET Core 3.1.2, Pomelo.EntityFramework 3.1.1 to link with a MySQL database. Here is a minimum example to demonstrate my problem.

Two model classes are defined. The model Field includes multiple zones:

public class Field
{
    [Key]
    public int Id { get; set; }
    public virtual ICollection<Zone> Zones { get; set; }

    public Field()
    {
        Zones = new HashSet<Zone>();
    }
}

public class Zone
{
    [Key]
    public int Id { get; set; }
    public int FieldId { get; set; }
    public virtual Field Field { get; set; }
}

Then an API is created to get the data for a zone.

[Route("api/field/{field}/zone/{id}")]
[HttpGet]
public async Task<ActionResult<List<Field>>> GetZone(
    [FromRoute] int field,
    [FromRoute] int id)
{
    Zone Zone = await _context.Zone
                              .Where(m => m.FieldId == field && m.Id == id)
                              .SingleOrDefaultAsync();
    return Ok(_context.Field);
}

In the demo code, I expect to return the list of Field without Zone. However, the results include the contents for Zone equals id if calling /api/field/16/zone/15.

[
    {
        "zone": [],
        "id": 7
    },
    {
        "zone": [
            {
                "id": 15
            }
        ],
        "id": 16
    }
]

It seems the contents are kept if the child is called in another place. I would not want to return child. Any suggestions?

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
Bangyou
  • 8,880
  • 14
  • 59
  • 90

2 Answers2

1

You can add [JsonIgnore] and [IgnoreDataMember] attributes in the Zones property in Field class.

 public class Field
        {
            [Key]
            public int Id { get; set; }
            [JsonIgnore]
            [IgnoreDataMember]
            public virtual ICollection<Zone> Zones { get; set; }

            public Field()
            {
                Zones = new HashSet<Zone>();
            }
        }

More details, please refer to this.

LouraQ
  • 5,824
  • 1
  • 4
  • 15
  • Thanks. However jsonignore attribute totally ignore in all API request. I would like to have it in other request. – Bangyou May 30 '20 at 11:21
0

The problem is related with Tracking behavior in Entity Framework Core. See this link for more information: https://docs.microsoft.com/en-us/ef/core/querying/tracking

Using function AsNoTracking() will solve my problem.

return Ok(_context.Field.AsNoTracking());
Bangyou
  • 8,880
  • 14
  • 59
  • 90