Error null reference in left join

Viewed 61

When i comment dishes.Add(new Dishes { DishID = 8, DishName = "Name", DishTypeID = 2, IngredientID = 2 }); i get in ll one item Amount="1 cup" DishID=1 Ingridient="egg" Name ="Soup". When uncomment that line raising error, null reference exception in b.IngredientTypeID. The main question how to get in ll two item's:

1) Amount="1 cup" DishID=1 Ingridient="egg" Name ="Soup"

2) Amount=null DishID=2 Ingridient=null Name =null

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        List<Dishes> dishes = new List<Dishes>();
        List<Ingredients> ingredients = new List<Ingredients>();
        List<Amount> amount = new List<Amount>();
        List<Ingredient> ingredient = new List<Ingredient>();

        dishes.Add(new Dishes { DishID = 1, DishName = "Soup", DishTypeID = 1, IngredientID = 1 });
        //dishes.Add(new Dishes { DishID = 8, DishName = "Name", DishTypeID = 2, IngredientID = 2 }); 
        ingredients.Add(new Ingredients { AmountID = 2, IngredientID = 1, IngredientTypeID = 1, IngredientUniqID = 1 });
        amount.Add(new Amount { AmountID = 2, AmountName = "1 cup" });
        ingredient.Add(new Ingredient { IngredientID = 1, IngredientName = "egg" });

        var test = from dish in dishes
                   join ing in ingredients on dish.IngredientID equals ing.IngredientID into result
                   from b in result.DefaultIfEmpty()
                   join i in ingredient on b.IngredientTypeID equals i.IngredientID into r
                   from c in r.DefaultIfEmpty()
                   join am in amount on b.AmountID equals am.AmountID into s
                   from t in s.DefaultIfEmpty()
                   select new DisplayRecipe { Name = dish.DishName, Amount = t.AmountName, Ingredient = c.IngredientName, DishID = dish.DishID };

        List<DisplayRecipe> ll = test.ToList();
    }
}
public partial class Dishes
{
    public int DishID { get; set; }
    public string DishName { get; set; }
    public Nullable<int> DishTypeID { get; set; }
    public Nullable<int> IngredientID { get; set; }
}

public partial class Ingredients
{
    public int IngredientID { get; set; }
    public Nullable<int> AmountID { get; set; }
    public Nullable<int> IngredientTypeID { get; set; }
    public int IngredientUniqID { get; set; }
}

public partial class Amount
{
    public int AmountID { get; set; }
    public string AmountName { get; set; }
}
public partial class Ingredient
{
    public int IngredientID { get; set; }
    public string IngredientName { get; set; }
}
public class DisplayRecipe
{
    public string Name { get; set; }
    public string Ingredient { get; set; }
    public string Amount { get; set; }
    public int DishID { get; set; }
}
}
2 Answers
Related