'How can I fully instantiate the Photo Entity

public class Child
{
    public int Cld { get; set; }
    public string ChildCode { get; set; }
    public string FirstName { get; set; }
    public string SurName { get; set; }
    public string Sex { get; set; }
    public DateTime DateOfBirth { get; set; }
    public DateTime  FoundRelinguished { get; set; }
    public DateTime Intake { get; set; }=DateTime.Now;
    public ICollection<ChildPhoto> ChildPhotos {get; set;}
}

public class ChildPhoto
{
    [Key]
    public int PhotocId { get; set;}
    public string FileName {get; set;}
    public string PhotoPath {get; set;}
    public bool IsMain {get; set;}
    public int ChildId {get; set;}
    public  Child Child {get; set;}
    public DateTime UploadDate {get; set;}=DateTime.Now;
}

public interface IChildRepository
{
    Task<Child> GetChildByIdAsync(int chd);
    Task<Child> AddChildrenAsync(Child child);
    Task<bool> SaveAllAsync();
}

The Controller method

public async Task<ActionResult> AddPhoto(int chd, [FromForm]IFormFile file) 
{ 
    // get the child througth repository
    var thechild = await _childRepository.GetChildByIdAsync(chd);
    if (thechild == null)
        return NotFound("The Child Adding his/her Photos was not found");
    var childid = thechild.Cld;
    var extension = Path.GetExtension(file.FileName);
    var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
    if (file == null) return BadRequest("Please Selecet a file");
    if (file.Length == 0) return BadRequest("The File Your Select is Empty");
    
    var folderName = Path.Combine(_host.WebRootPath, "ChildImages");
    if (!Directory.Exists(folderName))
    {
        Directory.CreateDirectory(folderName);
    }
    string photoPath = Path.Combine(folderName, fileName);
    using (var stream = new FileStream(photoPath, FileMode.Create))
    {
        await file.CopyToAsync(stream);
    }
    var photoPathDb = Path.Combine("ChildImages", fileName );
    var photo = new ChildPhoto 
    {
        PhotoPath = photoPathDb, 
        FileName = fileName, 
        ChildId= childid
    };
    
    if (thechild.ChildPhotos.Count == 0) 
    {
        photo.IsMain = true;
    }
    thechild.ChildPhotos.Add(photo);
    await _childRepository.SaveAllAsync();
    var photoToReturn = _mapper.Map<ChildPhoto, ChildPhotoDto>(photo);
    return CreatedAtRoute("GetPhoto", new { chd = thechild.Cld, id = photo.PhotocId }, photoToReturn);
}
{
 error:   "details": "   at API.Controllers.ChildPhotosController.AddPhoto(Int32 chd, IFormFile file) in C:\\Users\\USER\\Project\\GhAdoptionApp\\API\\Controllers\\ChildPhotosController.cs:line 82\r\n   at lambda_method32(Closure , Object )\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)\r\n   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)\r\n   at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)\r\n   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)\r\n   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)\r\n   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)\r\n   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)\r\n   at API.Middleware.ExceptionMiddleware.InvokeAsync(HttpContext context) in C:\\Users\\USER\\Project\\GhAdoptionApp\\API\\Middleware\\ExceptionMiddleware.cs:line 30",
    "statusCode": 500,
    "message": "Object reference not set to an instance of an object."
}

Please I have the entity for child and ChildPhotos, In the Controller I was called the a child through interface and the childrepository. but I get the Object reference not set to an instance of an object error.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source