0

I am looking for a savior to this my problem.

I am trying to follow this tutorial about Nested Collection:

Nested collection in MVC add multiple phone number

Nevertheless, I ran into a problem with this:

internal void CreatePart(int count = 1)
    {
        for (int i = 0; i < count; i++)
        {
            Parts.Add(new Part()); // ====>>>>>> it throws null reference
        }
    }

I could not find the source of the null. Can you please spot it for me?

here is my codes:

entity for product

public class Product
{
    public int Id { get; set; }

    [StringLength(50, MinimumLength = 2)]
    public string Name { get; set; }

    public virtual ICollection<Part> Parts { get; set; }
    public virtual ICollection<Version> Versions { get; set; }

    internal void CreatePart(int count = 1)
    {
        for (int i = 0; i < count; i++)
        {
            Parts.Add(new Part());
        }
    }
}

entity for parts

public class Part
{
    public int Id { get; set; }

    [StringLength(50, MinimumLength = 2)]
    public string Name { get; set; }

    public int ProductId { get; set; }
    public virtual Product Product { get; set; }

    public string DeletePart { get; set; }
}

Create controller:

public ActionResult Create()
    {
        var product = new Product();
        product.CreatePart(2);
        return View(product);
    }
Ace Supriatna
  • 235
  • 1
  • 4
  • 19

2 Answers2

3

You haven't actually instantiated Parts, so you get an exception when trying to add elements to it.

If you look at the example you linked to, you're missing a constructor in your Product class.

Try adding this to your class:

public Product()
{
    this.Parts = new HashSet<Part>();
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
0

Not entirely sure on this but!

Change this:

for (int i = 0; i < count; i++)
{
   Parts.Add(new Part());
}

To this:

for (int i = 0; i < count; i++)
{
   Part p = new Part(); 
   Parts.Add(p);
}

If the error is now moved to:

Part p = new Part(); << Here

Then I guess the problem is how it is getting initialised.

Could you try defining a constructor for the Part class and give it dummy values see what happens then.

GIVE-ME-CHICKEN
  • 1,239
  • 3
  • 15
  • 29