Linq:非静态方法需要一个具有选择新{model}的目标

Kar*_*ine 0 linq asp.net-mvc c#-4.0

我有此LINQ查询,它返回非静态方法异常,因为左联接有时会为context.Betas返回一个空值。

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();
Run Code Online (Sandbox Code Playgroud)

如果删除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:         }
Run Code Online (Sandbox Code Playgroud)

Guv*_*nte 5

您收到一个空引用异常。这被称为非静态目标异常,因为LINQ在后端使用反射来执行其操作。

CurrentUser = b.UserProfile == null ? null : b.UserProfile,
BetaId = b.Id == null ? 0 : b.Id,
Run Code Online (Sandbox Code Playgroud)

造成它,你需要做

CurrentUser = b == null ? null : b.UserProfile,
BetaId = b == null ? 0 : b.Id,
Run Code Online (Sandbox Code Playgroud)

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