问题描述
所以......我正在使用Entity Framework构建一个MVC Web应用程序。
我有三个EF类:Tasks,SubTasks和TaskCategory。 />
我已将关联/导航属性添加到我的实体框架"架构"中,所以它看起来像这样:
子任务---(pointsTo)--->任务---(pointsTo)---> TaskCategory
导航效果很好,鉴于那里是一个导航的对象引用。这是问题所在。
在我的MVC控制器中,我有一个排序机制,它接受一个sortOrder参数,然后检索该sortOrder中的数据。例如,如果我想订购"主"的子任务。任务按照主
任务的任务类别的名称,我会这样做:
So... I'm building an MVC web application, using Entity Framework.
I have three EF classes: Tasks, SubTasks and TaskCategory.
I have added associations/navigation properties to my Entity Framework "schema", so it looks like this:
Subtasks---(pointsTo)--->Tasks---(pointsTo)--->TaskCategory
Navigation works great, given that there is an object reference to navigate by. Here's the problem.
In my MVC controller, I have a sorting mechanism, that will accept a sortOrder parameter, which then retrieves the data in that sortOrder. For example, if I want to order the subtasks of a "master" task by the name of the task category for that master task, I would do this:
orderedSubTasks = subtasks.OrderBy(t => t.task.taskCategory.categoryName).ToList();
这也很有用,除了并非所有的Task对象都有关联的TaskCategory,即Task的TaskCategory属性为NULL。
这会导致错误:"对象引用未设置为对象的实例"
...这确实有意义,但我仍然想订购子任务,并且只是将"null-category"的子任务分组。任务一起。
怎么办?
-Jeppe
This also works great, except not all Task objects have an associated TaskCategory, that is, the TaskCategory property of the Task is NULL.
This results in an error: "object reference not set to an instance of an object"
...which does make sense, but still I would like to order the subtasks, and just group the subtasks of "null-category" tasks together.
What to do?
-Jeppe
推荐答案
orderedSubTasks = subtasks.OrderBy(t => (t.task.taskCategory != null) ? t.task.taskCategory.categoryName : String.Empty).ToList();
-Jeppe
-Jeppe
这篇关于按NULL导航会导致Universe崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!