简体   繁体   中英

Value cannot be null, r nparameter name source

I am confused. I have two statements that are the same and one works and the other receives the error - value cannot be null. r nparameter name source. From what I read I am receiving the error because something is null in my linq expression. However from what I can tell nothing is null.

The first if statement works. When a person selects 'Select' from a list of Burn Project a list of BurnPiles is displayed below the BurnProject list. (this works). Then when a person selects 'Select' from the list of BurnPiles a list of RequestedBurns is display below it. This gives me the null error. At one time it did work now it doesn't.

I am at a loss of what went wrong. I do know the RequestedBurn Table starts at record #2 but that shouldn't have anything to do with it. The BurnPile records that I have been using have associated RequestedBurns.

        //when 'Select' is chosen from the list of burn projects the list of burn piles 
        //associated with that specific burn project is display below it.
        if (burnerID != null)
        {
            ViewBag.BurnerID = burnerID.Value;
            viewModel.BurnPiles = viewModel.BurnProjects.Where(
                b => b.BurnerID == burnerID.Value).Single().BurnPiles;
        }

        //when 'Select' is chosen from the list of burn piles the list of requested 
        //burns associated with that specific burn pile is displayed below it.
        if (burnPileID != null)
        {
            ViewBag.BurnPilesID = burnPileID.Value;
            viewModel.RequestedBurns = viewModel.BurnPiles.Where(
                x => x.BurnPilesID == burnPileID).Single().RequestedBurns;

        }

If you look at documentation for Where or Single , you would see that source is the name of the parameter that represents your collection. So, it looks like you are trying to call a method on null reference, which would be the case if viewModel.BurnProjects = null or viewModel.BurnPiles = null .

viewModel.BurnPiles = viewModel.BurnProjects.Where(
            b => b.BurnerID == burnerID.Value).Single().BurnPiles;

could be setting viewModel.BurnPiles to null.

or

viewModel.BurnPiles.Where(
            x => x.BurnPilesID == burnPileID).Single()

is returning nothing so when you try and access RequestedBurns then it throws an exception.

SingleOrDefault also has an overload where you can simplify the expression a bit more. You can also combine it with the null conditional operator (if using at least C# 6).

if (burnerID != null)
{
    ViewBag.BurnerID = burnerID.Value;
    viewModel.BurnPiles = viewModel.BurnProjects.SingleOrDefault(b => b.BurnerID == burnerID.Value)?.BurnPiles;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM