Home > Net >  EntityFramework 6.0.0 child object gets removed when json with empty array was sent
EntityFramework 6.0.0 child object gets removed when json with empty array was sent

Time:12-01

I'm currently having issue in the API that uses Entity framework and AutoMapper library where

I tried to update a request detail by passing a JSON object with a property that has an empty array as value in the request body like so:

{
  "id": 1,
  "name": "user 2",
  "active": true,
  "photos": []
}

but before I sent the request, the object is like this:

{
  "id": 1,
  "name": "user 1",
  "active": false,
  "photos": [
    {
      "filename": "filename.jpg",
      "imageType": "img/jpeg"
    }
  ]
}

after I submitted the JSON to the api and fetch the new value, the "photos" property also became empty like so:

{
  "id": 1,
  "name": "user 2",
  "active": true,
  "photos": []
}

here is also method I called in API side

public ActionResult Update([FromBody] RequestViewModel body)
{
  using (var dbContext = new PrimaryDbContext())
  {
    var data = dbContext.Set<Request>().Include("Photos").Where(r => r.Id == body.Id).FirstOrDefault();

    if(data == null) return NotFound();

    Mapper.Map(body, data);

    dbContext.SaveChanges();

    return Ok(data);
  }
}

Its just weird because it don't remove the photos before when I am passing the JSON with empty array to the API. I just don't get why this issue occurred now

CodePudding user response:

It updated Photos too because you included them in your select query. Try to remove photos from select

var data = dbContext.Set<Request>()
                    .Where(r => r.Id == body.Id)
                    .FirstOrDefault();

CodePudding user response:

Instead of removing the Include() method that the entity framework loads, I just configured the AutoMapper to exclude the mapping of Photos when passing the RequestViewModel's value into Request's properties like so:

From

    CreateMap<RequestViewModel,Request>();

To

    CreateMap<RequestViewModel,Request>()
        .ForMember(r => r.Id,o => o.MapFrom(rvm => rvm.Id))
        .ForMember(r => r.Name,o => o.MapFrom(rvm => rvm.Name))
        .ForMember(r => r.Active,o => o.MapFrom(rvm => rvm.Active))
        .ForAllOtherMembers(o => o.Ignore());
  • Related