Linq:非静态方法 - 需求目标与选择新{模型} [英] Linq: Non-static-methods-requires-a-target with select new {model}

查看:3126
本文介绍了Linq:非静态方法 - 需求目标与选择新{模型}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个LINQ查询返回一个非静态方法异常,因为左连接有时返回一个null值为context.Betas。

I have this LINQ query that returns a Non-static-method exception, because the left join sometimes returns a null value for 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();

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

If I remove the CurrentUser and BetaId the query works, but I need to keep all information together. Could you help me please to solve that problem?

谢谢!

实际的例外是这样:

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

Non-static method requires a target. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

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


推荐答案

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

You are getting a null reference exception. It is called a non-static target exception since LINQ uses reflection in the backend to do its thing.

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。

Since the default value of a reference type is null.

这篇关于Linq:非静态方法 - 需求目标与选择新{模型}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆