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

时间:2013-05-14 09:22:07

标签: c# linq linq-to-sql

我在下面的查询中使用左外连接。变量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();

1 个答案:

答案 0 :(得分:2)

由于你正在进行左连接,我猜你想要包含空值。只需添加

where fgi == null || (....)

或者,如果您不希望空值只是将查询更改为内连接。