如何从 MVC 中的多个表中获取特定记录的详细信息 asp.net
本文关键字:记录 net 详细信息 获取 asp MVC | 更新日期: 2023-09-27 17:56:16
我有两个表StudentPersonalInformation
和EducationQualification
在MVC中,我创建了两个模型类StudentPersonalInformation.cs
和EducationQualification.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 显示详细信息。请告诉我该怎么做。
您应该创建一个 ViewModel,并在控制器操作中填充您希望视图具有的所有属性。
public class MyViewModelWithMultipleLists
{
public List<StudentPersonalInfo> Students{ get; set; }
public List<EducationQualification> Educations{ get; set; }
//etc
}
首先,
您需要通过向 EducationQualifications 添加导航属性来创建学生和资格之间的关系,假设每个资格有 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