none
Navigating by NULL causes universe to collapse RRS feed

  • Question

  • 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();

    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

    Thursday, December 27, 2018 10:10 AM

All replies

  • Solved it:

    orderedSubTasks = subtasks.OrderBy(t => (t.task.taskCategory != null) ? t.task.taskCategory.categoryName : String.Empty).ToList();
    
    

    -Jeppe
    Thursday, December 27, 2018 10:15 PM
  • Hi Jeppe,

    I am glad to know that you resolve the issue and thanks for sharing the solution to us, please mark it as answer, it will be beneficial to other communities who have the similar issue.

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, December 28, 2018 1:10 AM
    Moderator