ASP.NET Core只返回一个实体中集合的第一个值 [英] ASP.NET Core only returning first value of a collection in an entity
问题描述
我有一个MyEntity类,其中包含一个集合:
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; }
}
与课程一个很多的关系Step:
A one-many relationship with class Step:
public class Step
{
...
[ForeignKey("MyEntityForeignKey")]
public MyEntity { get; set; }
}
以下是返回指定MyEntity的API调用:
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());
}
运行这个时,一切看起来都很棒,除了集合。调试时,显示正确的值。即使我在这些集合中有2+项目,当它返回响应 Ok 时,它总是返回ProcessSteps集合中的第一个项目。
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.
编辑:
看起来像我的外键返回的回应是罪魁祸首。迭代和归零外键似乎有固定的东西。
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)
推荐答案
我有一个类似的问题,只有目标集合的第一个实体被返回,除非我设置为null,否则所有的内部引用。
但是我能够通过映射我的模型到dto对象(或ViewModel)返回之前。 dto通常是模型实体的一个子集。这样我就不用设置内部引用的空白了。
一般来说,我认为这是一个很好的做法,只需要把客户端只返回到严格需要的属性,而不给出整个模型对象。
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.
这篇关于ASP.NET Core只返回一个实体中集合的第一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!