簡體   English   中英

LINQ查詢中的空引用

[英]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(),

我認為解決此問題的最佳方法是將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
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM