Short Question: How do I call a getter explicitly without using the result and prevent compiler optimization from removing the call.
Longer Explanation of what I want to do
I'm using entity framework with web api to build a simple rest api. I'm using lazy-loading with proxies to realize one-to-many realations.
Now on a DELETE-Request I want to delete the entity including all child entities (this works fine). Then I want to return the deleted entity including children. This will fail because lazy-loading the children during serialization after DELETE obviously doesn't work.
[HttpDelete("{id}")]
public RolloutPlan Delete(int id)
{
var parent = _context.ParentEntities.Find(id);
_context.ParentEntities.Remove(parent);
_context.SaveChanges();
return parent; // lazy-loading children here will fail
}
So what I would like to do is to explicitly call the getter for the children before calling DELETE to load them beforehand:
[HttpDelete("{id}")]
public RolloutPlan Delete(int id)
{
var parent = _context.ParentEntities.Find(id);
var children = parent.Children; // lazy-load children before DELETE.
_context.ParentEntities.Remove(parent);
_context.SaveChanges();
return parent;
}
This will fail however because the compiler will remove the variable children as it is unused. If I do something with the variable children though it works fine:
[HttpDelete("{id}")]
public RolloutPlan Delete(int id)
{
var parent = _context.ParentEntities.Find(id);
var children = parent.Children; // lazy-load children before DELETE.
// prevent the compiler from removing the call to parent.Children
_logger.LogInformation("Children.Count:" + children.Count);
_context.ParentEntities.Remove(parent);
_context.SaveChanges();
return parent; // lazy-loading children here will fail
}
Edit: Lazy-Loading by adding an assignment does work (my mistake)
So what would be the best way to go about this issue? I guess there is a smart way to explizitly load the relation in entity framework that I'm currently unaware of and that would be the best solution for my issue. But I'm also really curious to know how solve this issue in general (calling getters explicilty).
Entites:
public class ParentEntity
{
public int? Id { get; set; }
public virtual ICollection<ChildEntity> Children { get; set; }
}
public class ChildEntity
{
public int Id { get; set; }
}