Referencia nula al llamar a una función de vacío interno dentro de una clase desde el controlador ASP MVC
Frecuentes
Visto 197 equipos
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?
aquí están mis códigos:
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);
}
2 Respuestas
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
clase.
Try adding this to your class:
public Product()
{
this.Parts = new HashSet<Part>();
}
contestado el 28 de mayo de 14 a las 12:05
Just for my learning, can anybody pls explain what does HashSet mean? - As Supriatna
Mr Grant, too bad your website is down. Should you in any way come to Indonesia, I will gladly assist you here. - As Supriatna
0
Not entirely sure on this but!
Cambia esto:
for (int i = 0; i < count; i++)
{
Parts.Add(new Part());
}
A esto:
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.
contestado el 28 de mayo de 14 a las 12:05
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas c# asp.net asp.net-mvc or haz tu propia pregunta.
product.Parts property is null? - scheien