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

如何将数据库列表转换为ViewModel列表?解决Students空引用异常

解决“未将对象引用设置到对象的实例”错误并正确映射家庭子女列表到ViewModel

嘿,这个空引用问题其实很常见——你看,你在ApplicantVm里声明了Students属性,但从来没给它初始化过具体的集合对象,所以当你尝试遍历applicantVm.Students的时候,它还是null,自然就报错了。咱们一步步来修复:

第一步:理解问题根源

IEnumerable<StudentVm>只是一个接口,它本身不代表任何实际的集合。你需要给它分配一个具体的实现(比如List<StudentVm>),才能往里添加元素。

第二步:修改控制器代码,正确初始化并填充数据

这里是调整后的代码,我加了注释说明每一步的作用:

public ActionResult Application() {
    var currentUserEmail = User.Identity.Name;
    var familyMembers = _db.sp_ApplicantFamily_SelectFamilyMembers(currentUserEmail).ToList();
    
    // 1. 初始化ViewModel实例
    ApplicantVm applicantVm = new ApplicantVm();
    
    // 2. 给Students属性初始化一个空的List集合(关键!解决空引用问题)
    applicantVm.Students = new List<StudentVm>();
    
    // 3. 遍历存储过程返回的家庭子女数据,逐个创建StudentVm并赋值
    foreach (var child in familyMembers) {
        var student = new StudentVm();
        // 映射对应属性(注意字段名要和存储过程返回的一致)
        student.FirstName = child.FirstName;
        student.DateOfBirth = child.ChildDateOfBirth; // 假设familyMembers里有这个字段
        student.Grade = child.Grade;
        // 如果需要设置SelectedGradeId,可以根据Grade匹配Grades选项
        // student.SelectedGradeId = applicantVm.Grades?.FirstOrDefault(g => g.Text == child.Grade)?.Value ?? 0;
        
        // 4. 将创建好的StudentVm添加到集合中
        ((List<StudentVm>)applicantVm.Students).Add(student);
    }
    
    // 别忘了给Grades属性赋值,不然视图里的年级下拉框会是空的
    // applicantVm.Grades = _db.Grades.Select(g => new SelectListItem { 
    //     Text = g.GradeName, 
    //     Value = g.Id.ToString() 
    // }).ToList();
    
    // 5. 把填充好的ViewModel传给视图
    return View(applicantVm);
}

可选优化:简化集合操作

如果你不想每次都把IEnumerable<StudentVm>转成List<StudentVm>,可以直接修改ApplicantVm里的属性类型:

// 把原来的IEnumerable改成List
public List<StudentVm> Students { get; set; }

这样初始化和添加元素会更简单:

applicantVm.Students = new List<StudentVm>();
// 直接添加,不需要强制转换
applicantVm.Students.Add(student);

视图层注意事项

确保视图里正确使用Model.Students来渲染列表,比如:

@model ApplicantVm

<h3>已注册的家庭子女</h3>
@if (Model.Students?.Any() == true)
{
    foreach (var student in Model.Students)
    {
        <div class="student-item">
            <p>姓名:@student.FirstName</p>
            <p>出生日期:@student.DateOfBirth.ToShortDateString()</p>
            <p>年级:@student.Grade</p>
        </div>
    }
}
else
{
    <p>暂无已注册的子女信息</p>
}

内容的提问来源于stack exchange,提问作者Curious-programmer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:58:37