2016-03-03 35 views
1

我填充一个视图模型实体模型时如何处理一些空条目:如何从两个查询填充来自多个LINQ

型号: 学生(姓名,老师,HomeroomName,HomeRoomLocation)

这两个查询是对于学生表和Homeroom表。学生没有分配课室是可行的。

var student = context.Student.where(c => c.stuid == studentId).SingleOrDefault(); 

var homeroom = context.HomeRoom.where(c => c.stuid == studentId).SingleOrDefault(); 

if(student != null) 
{ 
    Student student = new Student 
    { 
    Name = student.Name, 
    Teacher = student.Teacher.Name, 
    HomeRoomName = homeroom.Name, 
    HomeRoomLocation = homeroom.Location 
    }; 
} 

如果主窗口查询为空,这完全符合业务规则,所有事情都会发生。如果条件允许并返回一个模型,我可能会有一堆,但我宁愿一次完成。

我可以内联吗?在模型人口中?像

HomeRoom = homeroom.Name == null ? null : homeroom.Name, 
+0

使用'班主任= homeroom.Name == NULL? null:homeroom.Name'没有任何意义,它与HomeRoom = homeroom.Name'一样 –

回答

2

您需要检查什么是如果homeroom变量null与否:

HomeRoom = homeroom == null ? null : homeroom.Name, 

在C#6.0,你可以使用Null-Conditional Operator

HomeRoom = homeroom?.Name, 

空,条件运算符检查在调用之前操作数(本例中为homeroom变量)是否为财产,是逻辑上等同明确的代码将是如下:

(homeroom!= null) ? homeroom.Name : null 
2

这将允许你检查这两个变量为空,并创建对象,或创建一个学生,没有班主任,如果班主任为null。

if (student != null & homeRoom != null) { 
    Student student = new Student { 
     Name = student.Name, 
     Teacher = student.Teacher.Name, 
     HomeRoomName = homeroom.Name, 
     HomeRoomLocation = homeroom.Location 
    }; 
} else if (student != null) { 
    Student student = new Student { 
     Name = student.Name, 
     Teacher = student.Teacher.Name 
    }; 
} 
2

为什么你不在你的Student类中创建构造函数?

public Student() { 
} 

public Student(Student student, HomeRoom homeroom) { 
    this.Name = student.Name; 
    this.Teacher = student.Teacher.Name; 

    if(homeroom != null) { 
     this.HomeRoomName = homeroom.Name; 
     this.HomeRoomLocation = homeroom.Location; 
    } 
} 

所以,你可以使用这样的:

var newStudent = new Student(student, homeroom);