对于List <t> .Add </t>,“对象引用未设置为对象的实例”

时间:2014-10-02 12:33:25

标签: c# asp.net-mvc

在我的方法中,我有多个过滤数据,返回和对象的语句。因为我想用视图模型提供视图,所以我实例化一个列表然后将其传递给视图...

简化示例。

    List<viewModel> returnedViewModel = new List<viewModel>();

    foreach (var item in filteredData)
    {
        returnedViewModel.Add( // this line is throwing error
        new viewModel
        {
            data = item,
        });
    } 

问题在于我没有将对象引用设置为对象的实例。&#34;对于一个特定的filteredData对象的returnedViewModel.Add,而其他对象没有导致该问题。

我知道问题的可能来源不是解决方案。

我使用EF并在我的connectionString中有一个MARS语句。这可能是个问题吗?

整个陈述:

public ActionResult RenderPartialSearchableEventStacks(string viewType,
                                                       string orderColumn,
                                                       string sortOrder,
                                                       int? stackNumber,
                                                       string adminName,
                                                       string clientName,
                                                       string stackType,
                                                       string stackStatus,
                                                       int? adminId = null)
{
    IEnumerable<blsEventStack> eventStacks = unitOfWork.EventStackRepository.Filter(n => (stackNumber == null) || n.EventStackId == stackNumber,
                                                                                    n => (String.IsNullOrEmpty(adminName)) || n.ManagingAdminName.Contains(adminName),
                                                                                    n => (String.IsNullOrEmpty(clientName)) || n.RelatedClientName.Contains(clientName),
                                                                                    n => (String.IsNullOrEmpty(stackType)) || n.EventStackType.Contains(stackType),
                                                                                    n => (String.IsNullOrEmpty(stackStatus)) || n.EventStackLastEventStatus.Contains(stackStatus));

    IEnumerable<blsEventStack> viewTypeRelatedEventStacks = eventStacks;

    if (viewType == "allEventStacks")
    {
        viewTypeRelatedEventStacks = unitOfWork.EventStackRepository.GetAll();
    }

    if (viewType == "assignedEventStacks")
    {
        // Needed to filter out results with empty (unassigned) admin name
        viewTypeRelatedEventStacks = from x in eventStacks
                                     where x.ManagingAdminName != null
                                     select x;
    }

    if (viewType == "singleAdminAssignedEventStacks")
    {
        string singleAdminName;

        if (adminId != null)
        {
            // Gets admin name using adminId
            singleAdminName = unitOfWork.AdminRepository.GetById(adminId).AdminName;
        }
        else
        {
            MembershipUser admin = Membership.GetUser();

            blsAdmin loggedInAdmin = (from x in unitOfWork.AdminRepository.GetAll()
                                      where x.AdminEmail == admin.Email
                                      select x).FirstOrDefault();

            singleAdminName = loggedInAdmin.AdminName;

            ViewBag.adminView = true;
        }

        // Gets all eventStacks that belong to a give adminName
        viewTypeRelatedEventStacks = from x in eventStacks
                                     where x.ManagingAdminName == singleAdminName
                                     select x;

        ViewBag.adminId = adminId;
    }

    IEnumerable<blsEventStack> returnedEventStacks = viewTypeRelatedEventStacks;

    if (orderColumn == "stack")
    {
        if (sortOrder == "descendingStack")
        {
            returnedEventStacks = from x in viewTypeRelatedEventStacks
                                  orderby x.EventStackId descending
                                  select x;
            sortOrder = null;
        }
        else
        {
            returnedEventStacks = from x in viewTypeRelatedEventStacks
                                  select x;
            sortOrder = "descendingStack";
        }
    }

    if (orderColumn == "managingAdmin")
    {
        if (sortOrder == "descendingManagingAdmin")
        {
            returnedEventStacks = from x in viewTypeRelatedEventStacks
                                  orderby x.ManagingAdminName descending
                                  select x;
            sortOrder = null;
        }
        else
        {
            returnedEventStacks = from x in viewTypeRelatedEventStacks
                                  orderby x.ManagingAdminName
                                  select x;
            sortOrder = "descendingManagingAdmin";
        }
    }

    if (orderColumn == "relatedClient")
    {
        if (sortOrder == "descendingRelatedClient")
        {
            returnedEventStacks = from x in viewTypeRelatedEventStacks
                                  orderby x.RelatedClientName descending
                                  select x;
            sortOrder = null;
        }
        else
        {
            returnedEventStacks = from x in viewTypeRelatedEventStacks
                                  orderby x.RelatedClientName
                                  select x;
            sortOrder = "descendingRelatedClient";
        }
    }

    if (orderColumn == "stackType")
    {
        if (sortOrder == "descendingStackType")
        {
            returnedEventStacks = from x in viewTypeRelatedEventStacks
                                  orderby x.EventStackType descending
                                  select x;
            sortOrder = null;
        }
        else
        {
            returnedEventStacks = from x in viewTypeRelatedEventStacks
                                  orderby x.EventStackType
                                  select x;
            sortOrder = "descendingStackType";
        }
    }

    if (orderColumn == "latestEventTime")
    {
        if (sortOrder == "descendingLatestEventTime")
        {
            returnedEventStacks = from x in viewTypeRelatedEventStacks
                                  orderby x.EventStackLastEventTime descending
                                  select x;
            sortOrder = null;
        }
        else
        {
            returnedEventStacks = from x in viewTypeRelatedEventStacks
                                  orderby x.EventStackLastEventTime
                                  select x;
            sortOrder = "descendingLatestEventTime";
        }
    }

    if (orderColumn == "latestEventStatus")
    {
        if (sortOrder == "descendingLatestEventStatus")
        {
            returnedEventStacks = from x in viewTypeRelatedEventStacks
                                  orderby x.EventStackLastEventStatus descending
                                  select x;
            sortOrder = null;
        }
        else
        {
            returnedEventStacks = from x in viewTypeRelatedEventStacks
                                  orderby x.EventStackLastEventStatus
                                  select x;
            sortOrder = "descendingLatestEventStatus";
        }
    }

    List<ViewModelAllEventStacks> returnedViewModel = new List<ViewModelAllEventStacks>();

    foreach (var item in returnedEventStacks)
    {
        returnedViewModel.Add( 
        new ViewModelAllEventStacks
        {
            EventStack = item,
            AdminId = item.AdminEventLogs.FirstOrDefault().AdminId,
            ClientId = item.ClientEventLogs.FirstOrDefault().ClientId
        });
    }

    ViewBag.stackNumber = stackNumber;
    ViewBag.adminName = adminName;
    ViewBag.clientName = clientName;
    ViewBag.stackType = stackType;
    ViewBag.stackStatus = stackStatus;

    // ViewBag passing state of existing order
    ViewBag.sortOrder = sortOrder;

    // ViewBag passing view data (ex. assignedEventStacks, allEventStacks, etc.)
    ViewBag.viewType = viewType;

    return PartialView("BLS_AllEventStacks", returnedViewModel);
}

2 个答案:

答案 0 :(得分:2)

有四种可能的原因:

  1. 您在调试中的代码并不是实际运行的并且过时了。
  2. viewModel构造函数中有一个空例外。
  3. data属性中发生了一个空例外。
  4. 如评论中所述,您筛选出的一些代码实际上是将列表设置为null
  5. 基于已编辑的问题

    returnedViewModel.Add( 
        new ViewModelAllEventStacks
        {
            EventStack = item,
            AdminId = item.AdminEventLogs.FirstOrDefault().AdminId,
            ClientId = item.ClientEventLogs.FirstOrDefault().ClientId
        });
    

    如果没有AdminEventLogsClientEventLogs,则会抛出空异常错误。也可能但不太可能,item为空。

答案 1 :(得分:1)

我相信这两行都是问题所在。当您使用item.AdminEventLogs.FirstOrDefault()时,如果item.AdminEventLogs没有任何元素,则该值为空,因此访问.AdminId会引发错误。同样的事情也适用于item.ClientEventLogs.FirstOrDefault()

AdminId = item.AdminEventLogs.FirstOrDefault().AdminId,
ClientId = item.ClientEventLogs.FirstOrDefault().ClientId

您可以使用.Any()来检查item.AdminEventLogsitem.ClientEventLogs是否包含任何元素。如果是,请使用第一个元素的AdminIdClientId,否则将AdminIdClientId设置为0(假设AdminIdClientId为整数)的

AdminId = item.AdminEventLogs.Any() ? item.AdminEventLogs.First().AdminId : 0,
ClientId = item.ClientEventLogs.Any() ? item.ClientEventLogs.First().ClientId : 0