在一对多关系.net实体框架中以一种视图显示数据

时间:2018-11-12 07:47:13

标签: c# .net asp.net-mvc entity-framework one-to-many

我的数据库中有两个表:Student(许多)和Department(一个),以及一对多关系。我想为每个StudentName显示带有DepartmentName的列表,但出现此错误:System.NullReferenceException:对象引用未设置为对象的实例。

这是我的控制器代码(该代码适用于一对一关系)

        public ActionResult Index()
    {

        List<Students> studlist = db.Students.ToList();
        StudentViewModel studlistVM = new StudentViewModel();

        List<StudentViewModel> studlistVMList = studlist.Select(x => new StudentViewModel
        {
            StudID = x.StudID,
            StudName = x.StudName,
            DeptName = x.deptobj.DeptName


        }).ToList();


        return View(studlistVMList);
    }

1 个答案:

答案 0 :(得分:1)

A,您忘了向我们展示您的课程。如果遵循entity framework code first conventions,则将具有与以下内容类似的类:

class Department
{
    public int Id {get; set;}
    ...

    // Every department has zero or more Students (one-to-many)
    public virtual ICollection<Student> Students {get; set;}
}

class Student
{
    public int Id {get; set;}
    ...

    // every Student belongs to exactly one department, using foreign key
    public int DepartmentId {get; set;}
    public virtual Department Department {get; set;}
}

还有您的DbContext

class UniversityContext : DbContext
{
     public DbSet<Department> Departments {get; set;}
     public DbSet<Student> Students {get; set;}
}

这是Entity Framework识别表,表中的列以及表之间的一对多关系所需要了解的全部信息

  

注意:在实体框架中,表中的列由   非虚拟属性。虚拟属性代表关系   在表之间

虚拟属性使您的生活更加轻松,因为您不必再​​进行(组)联接。只需使用虚拟集合,实体框架会将其转换为适当的联接。

  

我想为每个StudentName显示一个带有DepartmentName的列表,

var result = universityDbContext.Students
    .Where(student => ...)                 // only if you don't want all Students
    .Select(student => new
    {
        // select only the properties you plan to use
        Id = student.Id,
        StudentName = student.Name,

        DepartmentName = student.Department.Name,
    });

因为您使用过student.Department,所以实体框架知道需要SQL join

  

如果要使用平面SQL连接,请从“许多”侧开始,然后使用   虚拟财产的“一”方。如果要分组加入,请开始   与“一个”侧并使用虚拟ICollection来“多个”   一侧。

您想要一个平口联接,但是如果您想要Departments with their Students,您会做类似的事情:

var result = myDbContext.Departments
    .Where(department => ...)             // if you don't want all departments
    .Select(department => new
    {
        // select only the properties you plan to use
        Id = department.Id,
        Name = department.Name,

        StudentsWithHighGrades = department.Students
            .Where(student => student.Grade >= ...)
            .Select(student => new
            {
                Id = student.Id,
                Name = student.Name,
                Grade = student.Grade,
                ...
            })
            .ToList();
    });