0

Here's my annonce model :

    public class Annonce
    {
       ... 
       public int ID { get; set; }
       public ICollection<Piece>? Pieces { get; set; }
     }
       
    public class Piece
    {
    public int Id { get; set; }

    [Display(Name = "Type de pièce")]
    public Ty   pePiece Typepiece { get; set; }

    [Display(Name = "Superficie")]
    [Range(1, ushort.MaxValue)]
    [Required(ErrorMessage = "La superficie est requise.")]
    public int Superficie { get; set; }
    }

public class PieceTemp
{
    public int ID { get; set; }
    
    public string userID { get; set; }
    
    [Display(Name = "Type de pièce")]
    public TypePiece Typepiece { get; set; }

    [Display(Name = "Superficie")]
    [Range(1, ushort.MaxValue)]
    [Required(ErrorMessage = "La superficie est requise.")]
    public int Superficie { get; set; }
}

I get a error message on the line "annonce.Pieces.Add(p);" with the following code :

foreach (PieceTemp pt in _context.PiecesTemp.Where(pt => pt.userID == userID))
            {
                Piece p = new Piece
                {
                    
                    Typepiece = pt.Typepiece,
                    Superficie = pt.Superficie
                };
                
                annonce.Pieces.Add(p);
            }

The error message is : System.NullReferenceException : 'Object reference not set to an instance of an object.'

I don't understand because the p object is well instanciated before the add instruction.

Help would be really appreciated.

Thanks,

Sylvain

  • 2
    I suspect that either `announce` or `announce.Pieces` is null. We don't know anything about where `annonce` has come from, but that's what you should check, e.g. in the debugger or with logging. – Jon Skeet Sep 30 '22 at 06:29
  • I've changed "annonce.Pieces.Add(p);" by annonce.Pieces?.Add(p); . There's no error anymore but It doesn't add the piece object to the annonce. It doesn't do anything ! I really don't understand why. – SylvainKrier Sep 30 '22 at 13:59
  • 1
    Hint: what's the value of `annonce.Pieces`? Where do you expect it to become non-null? – Jon Skeet Sep 30 '22 at 14:00
  • annonce.Pieces remains null. I don't understand because the Add method should add an element. – SylvainKrier Oct 01 '22 at 20:36
  • 1
    What exactly do you think it should add an element *to*, if `annonce.Pieces` is null? *There's no list for it to be added to.* – Jon Skeet Oct 01 '22 at 20:45
  • I understand, All I need to do is to instanciate the list before adding elements with ();> thanks a lot for your support @JonSkeet – SylvainKrier Oct 02 '22 at 08:43

0 Answers0