LINQ查询中的空引用

时间:2014-03-04 19:45:51

标签: c# linq

我将尝试尽我所能地说出这一点。我目前正在尝试获取名为Program的值,但我的LINQ查询有问题

Interactions = new BindableCollection<InteractionDTO>(_client.Interactions.
    Select(x => new InteractionDTO
    {         
       Id = x.Id,
       ClientName = x.Person.CorrespondenceName,
       Indepth = x.Indepth,
       Program = x.Allocations.FirstOrDefault(y => y.Interaction_Id == x.Id).Program.Value,
       Category = x.Allocations.FirstOrDefault().Category.Value,
       ActivityDate = x.ActivityDate,
       Type = x.Type,
       Subject = x.Subject,
       LoanApplicationProvided = x.LoanApplicationProvided,
       BusinessPlanProvided = x.BusinessPlanProvided
    }));

我得到的错误是Object reference not set to an instance of an object.

当我在下面发表评论时,它有效但Program未通过。

Program = x.Allocations.FirstOrDefault(y => y.Interaction_Id == x.Id).Program.Value,
Category = x.Allocations.FirstOrDefault().Category.Value

我在LINQ查询中的目标:必须查找互动,然后从Program获取CategoryID / InterActionAllocations,然后从InteractionPrograms获取“值”。< / p>

Program.cs的

// Primary Keys -------------------------------------------------------
public int Id { get; set; }

[InverseProperty("Interaction")]
public virtual ICollection<InteractionAllocation> Allocations { get; set; }

InteractionAllocation.cs

// Associations -------------------------------------------------------
public int Interaction_Id { get; set; }

[ForeignKey("Interaction_Id")]
public virtual Interaction Interaction { get; set; }

public int? Category_Id { get; set; }

[ForeignKey("Category_Id")]
public InteractionCategory Category { get; set; }

2 个答案:

答案 0 :(得分:2)

似乎至少有一个互动没有相应的程序。您需要子查询来支持这种情况。一种简单的方法是在调用FirstOrDefault之前将程序转换为程序值

Program = x.Allocations.Where(y => y.Interaction_Id == x.Id)
    .Select(y => y.Program.Value)
    .FirstOrDefault(),

答案 1 :(得分:1)

我认为解决此问题的最佳方法是将ProgramCategory存储为中间结果,然后使用条件运算符(?)。这在综合语法中使用let关键字效果更好:

from i in _client.Interactions
let program = x.Allocations.Where(y => y.Interaction_Id == x.Id)
                           .Select(a => a.Program).FirstOrDefault()
let cat = x.Allocations.Select(a => a.Category).FirstOrDefault()
select new InteractionDTO
    {         
       Id = x.Id,
       ClientName = x.Person.CorrespondenceName,
       Indepth = x.Indepth,
       Program = program == null ? null : program.Value,
       Category = cat == null ? null : cat.Value,
       ActivityDate = x.ActivityDate,
       Type = x.Type,
       Subject = x.Subject,
       LoanApplicationProvided = x.LoanApplicationProvided,
       BusinessPlanProvided = x.BusinessPlanProvided
    }