[英]Null reference in LINQ query
我将尽我所能来表达这句话。 我目前正在尝试获取一个名为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.
为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查询中获得的目标是:必须查找交互,然后从InterActionAllocations
获取Program
/ CategoryID
,然后从InteractionPrograms
获取“值”。
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; }
似乎您的互动中至少有一个没有相应的程序。 您需要子查询来支持这种情况。 一种简单的方法是在调用FirstOrDefault
之前将程序转换为程序值:
Program = x.Allocations.Where(y => y.Interaction_Id == x.Id)
.Select(y => y.Program.Value)
.FirstOrDefault(),
我认为解决此问题的最佳方法是将Program
和Category
存储为中间结果,然后使用条件运算符( ?
)。 与综合语法中的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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.