如果只有对象的数据可以从视图模型中获得,则在linq中连接数据
本文关键字:数据 连接 linq 则在 模型 对象 如果 视图 | 更新日期: 2023-09-27 18:03:55
我有viewModel提取多个模型类。我绑定数据,然后传递到剃刀部分视图显示数据,但我得到错误,如果一个模型对象为空。在我的业务流程中,这是预期的,但我的问题是,如果条件是Linq- Joins,即只有当数据存在于数据库中,或者有更好的方法来做,我可以使用。
public StudentDetailedProfileViewModel GetStudentDetailedProfileByStudentID(int _studentID)
{
try
{
using (var _uow = new StudentProfile_UnitOfWork())
{
StudentDetailedProfileViewModel StudentProfileObject = new StudentDetailedProfileViewModel();
var _profile = (from _student in _uow.Student_Repository.GetAll()
join _contactDetail in _uow.ContactDetail_Repository.GetAll() on _student.StudentID equals _contactDetail.StudentID
join _addressDetail in _uow.Address_Repository.GetAll() on _student.StudentID equals _addressDetail.StudentID
join _studentCourse in _uow.Course_Repository.GetAll() on _student.StudentID equals _studentCourse.StudentID
join _school in _uow.School_Repository.GetAll() on _studentCourse.SchoolID equals _school.SchoolID
join _campus in _uow.Campus_Repository.GetAll() on _studentCourse.CampusID equals _campus.CampusID
where _student.StudentID == _studentID
select new StudentDetailedProfileViewModel { _studentModel = _student, _contactDetailModel = _contactDetail, _addressModel = _addressDetail , _courseModel = _studentCourse,_schoolModel = _school, _campusModel = _campus}).FirstOrDefault();
_profile._emergencyContactModel = (from _emergencyContact in _uow.EmergencyContact_Repository.GetAll()
where _emergencyContact.StudentID == _studentID
select _emergencyContact).ToList();
return _profile;
}
}//
catch { return null; }
}
……
public class StudentDetailedProfileViewModel
{
public StudentDetailedProfileViewModel() { }
public Student _studentModel { get; set; }
public Course _courseModel { get; set; }
public School _schoolModel { get; set; }
public Campus _campusModel { get; set; }
public ContactDetail _contactDetailModel { get; set; }
public Address _addressModel { get; set; }
public List<EmergencyContact> _emergencyContactModel { get; set; }
}
如果您的根实体(Student)具有到子集合的导航属性(并且在您的实体模型中配置了关联),则可以使用Include()来代替join。让LINQ生成select语句,而不是试图事先找出它。