如何从asp.net MVC中的多个表中获取特定记录的详细信息

时间:2014-04-03 08:46:41

标签: c# asp.net asp.net-mvc entity-framework asp.net-mvc-4

我有两张表StudentPersonalInformationEducationQualification

在MVC中,我创建了两个模型类StudentPersonalInformation.csEducationQualification.cs,这里我在一个包装类中创建了两个类的对象,并且类名为StudentInfo.cs

public class StudentPersonalInfo {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string StudentFirstName { get; set; }
    public string StudentLastName { get; set; }
    public int Age { get; set; }
    public string BloodGroup { get; set; }
    public string Address { get; set; }

}

public class EducationQualification {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Graduation { get; set; }
    public int Grad_Marks_obtain { get; set; }

    public string Grad_passing_year { get; set; }
    public stringPost Graduation { get; set; }

    public int PG_Marks_obtain { get; set; }
    public string PG_passing_year { get; set; }    
}

public class StudentInfo    
{
    public StudentPersonalInfo PersonalInfo { get; set; }
    public EducationQualification EducationalQualification { get; set; }
}

这是DBContext类:

public class StudentDbContext:DbContext
{
    public DbSet<StudentPersonalInfo> StudentPersonalInfos { get; set; }
    public DbSet<EducationQualification> EducationQualifications { get; set; }
}

我的问题是:

如何在一个视图中按两个表中特定学生的ID显示详细信息。 请告诉我怎么做...

2 个答案:

答案 0 :(得分:1)

您应该创建一个ViewModel,并且在控制器操作中,您应该填充您希望视图具有的所有属性。

public class MyViewModelWithMultipleLists
{
       public List<StudentPersonalInfo> Students{ get; set; } 
       public List<EducationQualification> Educations{ get; set; }
       //etc
}

答案 1 :(得分:0)

首先,您需要通过向EducationQualification添加导航属性来创建学生和资格认证之间的关系,假设每个资格认证都有1名学生。

public virtual Student Student {get; set;}

如果学生可以拥有多项资格,那么您的StudentInfo模型更有可能是这样的:

    public StudentPersonalInfo PersonalInfo { get; set; }
    public List<EducationQualification> EducationalQualification { get; set; }

那么你可以查询数据库,因为你已经创建了学生和资格之间的关系,你的查询将类似于:

var model= (from s in Student
where s.Id = id
select new StudentInfo
{
    PersonalInfo = s,
    EducationalQualification = s.EducationQualification.ToList()
}).FirstOrDefault()

你会传递结果:

return View(model);

到强类型视图:

    @model StudentInfo

   @Html.DisplayFor(x => x.PersonalInfo.StudentFirstName)
   ...etc