I have a class MyEntity with a collection within it:
public class MyEntity
{
[Key]
public int MyId { get; set; }
[Display(Name = "Process Name")]
public string ProcessName { get; set; }
public ICollection<Step> ProcessSteps { get; set; }
}
A one-many relationship with class Step:
public class Step
{
...
[ForeignKey("MyEntityForeignKey")]
public MyEntity { get; set; }
}
Below is the API call to return a specified MyEntity:
public async Task<IActionResult> MyEntity(int? id)
{
if (id == null)
{
return Ok(await _context.MyEntity.ToListAsync());
}
var process = _context.MyEntity.Where(f => f.MyId == id).Include(g => g.ProcessSteps);
if (process.Count() == 0)
{
return NotFound();
}
return Ok(process.First());
}
When running this, everything looks great except for the collection. While debugging, the correct values are shown. Even though I have 2+ items in these collections, it always returns just the first item in the ProcessSteps collection from MyClass when it returns the response Ok.
Edit:
It looks like returning the response with my foreign key attached was the culprit. Iterating through and nulling the foreign key seems to have fixed things.
foreach (Step step in MyEntity.ProcessSteps)
{
Step.MyEntity = null;
}
return Ok(MyEntity.ProcessSteps)
I had a similar issue, where only the first entity of the target collection was returned unless I was setting to null all the inner references.
However I was able to solve this by mapping my model to dto object (or ViewModel) before returning it. The dto has usually a subset of the model entity. In this way I did not have to set to null the inner references.
In general I think it is a good practice to return to the client only the properties that are strictly needed, without giving the whole model object.