2013-06-05 50 views
0

我有这个LINQ查询返回非静态方法异常,因为左连接有时会为context.Betas返回一个空值。Linq:Non-static-methods-requires-a-target with select new {model}

return (from t in context.Alphas 
       join b in context.Betas on new { Id = t.Id } equals new { Id = b.AlphaId } into b_leftjoin 
       from b in b_leftjoin.DefaultIfEmpty() 
       where 
        t.UserProfileId == userProfileId 
        && t.IsClosed == false 
        && t.IsCancel == false 
        && t.EndDate <= DateTime.Now 
       orderby 
        t.Title 
       select new AlphaSelection() 
       { 
        Title = t.Title, 
        CurrentUser = b.UserProfile == null ? null : b.UserProfile, 
        BetaId = b.Id == null ? 0 : b.Id, 
        ProjectNumber = t.ProjectNumber, 
        AlphaId = t.Id 
       }).ToList(); 

如果我删除CurrentUser和BetaId查询工作,但我需要保留所有信息在一起。你能帮我解决这个问题吗?

谢谢!


编辑(回答到评论):

实际的例外是这个:

非静态方法需要一个目标。 描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪以获取有关该错误的更多信息以及源代码的位置。

Exception Details: System.Reflection.TargetException: Non-static method requires a target. 

Source Error: 


Line 39:    else 
Line 40:    { 
Line 41:     return query.ToList(); 
Line 42:    } 
Line 43:   } 
+1

什么是**实际**异常? –

+0

你能给出例外的*确切的*细节吗?目前还不清楚。 –

+0

'Id'的类型是什么?你为什么使用'new {}'来进行连接? – Guvante

回答

4

您正在收到空引用异常。它被称为非静态目标异常,因为LINQ在后端使用反射来完成它的事情。

CurrentUser = b.UserProfile == null ? null : b.UserProfile, 
BetaId = b.Id == null ? 0 : b.Id, 

原因造成的,你需要做的

CurrentUser = b == null ? null : b.UserProfile, 
BetaId = b == null ? 0 : b.Id, 

由于引用类型的默认值为null。

+0

或者你可以使用'??'而不是'whatever == null? defaultval:whatever' –

+0

真的很好!非常感谢你!! = D – Karine

+0

@newStackExchangeInstance:不是在这种情况下,他的原始格式是这种形式,但正确的版本不是,当最终结果使用“b”的一部分时,条件检查'b'。 – Guvante