2014-03-04 21 views
0

我會嘗試將這個短語盡我所能。目前,我想要抓住一個叫Program的價值,但我有我的LINQ查詢的麻煩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查詢我的目標:有擡頭的交互門,然後從InterActionAllocationsProgram/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; } 
+1

您需要花費一些時間進行調試。要麼分配爲空,要麼沒有一個具有正確的interaction_id,要麼有空程序,要麼類別爲空。 –

回答

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 
    } 
2

這似乎是你的相互作用的至少一個不具有相應的程序。你需要子查詢來支持這種情況。一個簡單的辦法就是之前做節目與節目價值的轉型呼喚FirstOrDefault

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