【问题标题】:Entity not being added to another entities collection实体未添加到另一个实体集合
【发布时间】:2021-03-04 18:19:59
【问题描述】:

我有一个应用程序,用户可以创建一个活动,然后在创建该活动后向该活动添加一张照片。这是事件实体:

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

这里是 EventPhoto 实体:

[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; }
    }

我的控制器中有一个方法可以将照片添加到现有事件中。这是之前配置该方法的方式:

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;

}

使用此代码,错误:object reference not set to an instance of an object 被抛出此行:existingEvent.Photos.Add(photo);

为防止出现此错误,我添加了空条件运算符:existingEvent.Photos?.Add(photo);。这可以防止在该代码行中引发特定错误,但我遇到的问题是照片实体没有被添加到现有事件照片中,因此 _context.SaveChangesAsync() 没有被触发,因为没有任何更改实体。

任何想法我哪里出错了?

【问题讨论】:

    标签: c# asp.net entity-framework


    【解决方案1】:

    您的问题是existingEvent.Photos 为空。

    当您执行 existingEvent.Photos?.Add(photo); 时,这只是在 Add 为空时跳过它。

    您应该尝试执行以下操作,如果它为空,它将分配并创建一个新列表,然后添加 Photo

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

    【讨论】:

    • 非常感谢!这似乎已经解决了这个错误。我现在似乎有一个不同的错误,但我必须单独调查。只是让我知道这里发生了什么……?? null 合并运算符检查 existingEvents.Photos 是否为 null,如果是,则初始化 new List。然后可以将照片添加到照片的列表中,因为它已经初始化。对吗?
    • 是的,没错,因为existingEvent.Photos?.Add(photo); 相当于做if(existingEvent.Photos != null) existingEvent.Photos.Add(photo)
    • 感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 2019-12-05
    相关资源
    最近更新 更多