ASP.NET Core only returning first value of a collection in an entity

百般思念 提交于 2019-12-06 14:59:54

问题


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)

回答1:


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.



来源:https://stackoverflow.com/questions/38731056/asp-net-core-only-returning-first-value-of-a-collection-in-an-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!