【发布时间】: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