You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历IEnumerable<object>?数据库数据展示遍历问题

问题解决:正确遍历数据库数据展示到表格

错误原因

你视图里的嵌套foreach完全多余——Model.Pacientes中的每个paciente本身就是包含所有属性的单个数据对象,不是可枚举的集合,内层遍历毫无意义,反而会导致无法正确访问属性。

最优解决方案:使用强类型DTO

1. 创建数据传输对象(DTO)

先定义一个强类型类来封装返回的数据,避免用object类型导致的类型丢失问题:

public class PacienteDto
{
    public int Id { get; set; }
    public string Nombres { get; set; }
    public string Apellidos { get; set; }
    public string Genero { get; set; }
    public string Telefono { get; set; }
    public DateTime FechaNacimiento { get; set; }
    public string Ciudad { get; set; }
}

2. 修改后端方法

将返回类型改为IEnumerable<PacienteDto>,同时用更规范的join替代交叉查询:

public IEnumerable<PacienteDto> ObtenerTodos()
{
    var pacientes = from p in _context.Pacientes
                    join p1 in _context.Personas on p.IdPersona equals p1.IdPersona
                    select new PacienteDto
                    {
                        Id = p1.Id,
                        Nombres = p1.Nombres,
                        Apellidos = p1.Apellidos,
                        Genero = p1.Genero,
                        Telefono = p1.Telefono,
                        FechaNacimiento = p.FechaNacimiento,
                        Ciudad = p.Ciudad
                    };
    return pacientes.ToList();
}

3. 修改视图代码

去掉内层foreach,直接遍历每个paciente并访问属性:

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Nombres</th>
            <th>Apellidos</th>
            <th>Género</th>
            <th>Teléfono</th>
            <th>Fecha de Nacimiento</th>
            <th>Ciudad</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var paciente in Model.Pacientes)
        {
            <tr>
                <td>@paciente.Id</td>
                <td>@paciente.Nombres</td>
                <td>@paciente.Apellidos</td>
                <td>@paciente.Genero</td>
                <td>@paciente.Telefono</td>
                <td>@paciente.FechaNacimiento.ToString("yyyy-MM-dd")</td>
                <td>@paciente.Ciudad</td>
            </tr>
        }
    </tbody>
</table>

临时方案(不推荐):使用dynamic类型

如果暂时不想创建DTO,可以用dynamic类型绕过类型检查,但会丢失智能提示和类型安全:

@foreach (dynamic paciente in Model.Pacientes)
{
    <tr>
        <td>@paciente.Id</td>
        <td>@paciente.Nombres</td>
        <!-- 其他属性同上 -->
    </tr>
}

内容的提问来源于stack exchange,提问作者Victor Alarcon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 22:45:39