如果只有视图模型中的对象数据可用,则在linq中连接数据 - ASP.net -mvc5

时间:2015-07-22 12:05:17

标签: c# asp.net-mvc linq

我有viewModel提取多个模型类。我绑定数据然后传递到剃刀局部视图以显示数据,但是如果其中一个模型对象为null,则会收到错误。在我的业务流程中,我的问题是,如果条件是Linq - 连接,我可以使用,即只有数据存在于数据库中或者有更好的方法才能连接结果。

 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; }

}

1 个答案:

答案 0 :(得分:1)

如果您的根实体(Student)具有子集合的导航属性(并且在您的实体模型中配置了关联),则可以包含()它们,而不是JOINing。让LINQ生成select语句,而不是事先尝试解决它。​​