Bail P
Bail P

Reputation: 281

Entity not being added to another entities collection

I have an app when a user can create an event and then add a photo to that event once the event has been created. This is the Event entity:

public class Event
    {
        public int Id { get; set; }
        public AppUser Creator { get; set; }
        public int CreatorId { get; set; }
        public ICollection<EventPhoto> Photos { get; set; }
}

Here is the EventPhoto entity:

[Table("EventPhoto")]

    public class EventPhoto
    {
        public int Id { get; set; }
        public string publicId { get; set; }
        public string Url { get; set; }
        public Event Event { get; set; }
        public int EventId { get; set; }
    }

I have a method in my controller which adds the photo to the existing event. This is how the method was previously configured:

public async Task<ActionResult<bool>> AddPhoto(IFormFile file, int id)
  {
            var existingEvent = await _eventsRepository.GetEventByIdAsync(id);
       
        var result = await _photoService.AddPhotoAsync(file); 

        if (result.Error != null) return BadRequest(result.Error.Message);

             var photo = new EventPhoto // This correctly creates the EventPhoto class and assigns the URL and public id correctly
            {
                Url = result.SecureUrl.AbsoluteUri,
                publicId = result.PublicId

            };

            existingEvent.Photos.Add(photo);

            return await _context.SaveChangesAsync() > 0;

}

With this code, the error: object reference not set to an instance of an object was being thrown at this line: existingEvent.Photos.Add(photo);.

To prevent this error, I added the null conditional operator: existingEvent.Photos?.Add(photo);. This prevented that particular error being thrown at that line of code but the issue I have is that the photo entity is not being added to the existing events photos and therefore the _context.SaveChangesAsync() is not being triggered as there haven't been any changes to the entity.

Any ideas where I am going wrong?

Upvotes: 0

Views: 26

Answers (1)

Shoejep
Shoejep

Reputation: 4839

Your problem is that existingEvent.Photos is null.

When you do existingEvent.Photos?.Add(photo); that's just skipping the Add when it's null.

You should try doing the below, which will assign and create a new List if it's null and then adds the Photo

existingEvent.Photos = existingEvent.Photos ?? new List<EventPhoto>();
existingEvent.Photos.Add(photo);

Upvotes: 1

Related Questions