Linq左外连接对象引用未设置为对象的实例

本文关键字:对象 实例 设置 连接 对象引用 Linq | 更新日期: 2023-09-27 18:13:20

我在下面的查询中使用左外连接。变量fgi是空的,所以在它给出对象引用错误的那一行。如何解决?

 var a = (from e1 in _db.Features.ToList()                                             
                                         where e1.int_ParentId==0 && e1.bit_IsModule == true & e1.bit_ShowInMenu == true && e1.bit_Activate == true                                
                                         join e2 in _db.OrganizationModules on e1.int_FeatureId equals e2.int_FeatureId into fg
                                         from fgi in fg.DefaultIfEmpty()
                                         where fgi.bit_OrganizationModuleActiveDeactive != false && fgi.int_OrganizationId == SepiaCMS.Models.Security.Authorization.OrganizationID   // object reference not set to instance of an object                                                                                   
                                         orderby e1.int_FeaturesSortID ascending, e1.int_FeatureId descending
                                         select new FeatureViewModel
                                         {
                                             featureid = e1.int_FeatureId,
                                             featurename = e1.vcr_FeaturesName,
                                             classes = path == e1.vcr_LinkName ? "<li class=active>" + Html.ActionLink(e1.vcr_FeaturesName, e1.vcr_LinkName.Substring(e1.vcr_LinkName.IndexOf('/') + 1), e1.vcr_LinkName.Substring(0, e1.vcr_LinkName.IndexOf('/')), new { area = string.IsNullOrEmpty(e1.vcr_Area) == true ? "" : e1.vcr_Area }, new { @class = e1.vcr_CssClass }) + "</li>" : "<li>" + Html.ActionLink(e1.vcr_FeaturesName, e1.vcr_LinkName.Substring(e1.vcr_LinkName.IndexOf('/') + 1), e1.vcr_LinkName.Substring(0, e1.vcr_LinkName.IndexOf('/')), new { area = string.IsNullOrEmpty(e1.vcr_Area) == true ? "" : e1.vcr_Area }, new { @class = e1.vcr_CssClass }) + "</li>"
                                         }).ToList();

Linq左外连接对象引用未设置为对象的实例

因为你正在做一个左连接,我猜你想要包括空值。只需添加

where fgi == null || (....)
如果您不想要空值,只需将查询更改为内部连接。