Null reference exception when using "insertManyAsync()".Net Driver

subashree

New member
Joined
Mar 15, 2021
Messages
1
Programming Experience
5-10
I am using Mongo Db .NetDriver . I am trying to insert bulk data to the db using “inserManyAsync()”
I am receiving the following Exception “Object Reference not set to instance of an object”.Please find the code below:


Iam getting the null reference when the method await _repo.RegisterMultipleDevice(devices); is called .Please let know what am I missing. Thanks

Controller

C#:
[HttpPost]

public async Task<IActionResult> FileUpload(IFormFile file)
{
    if (file == null || file.Length == 0)
    {
        return Content("Please upload  a file");
    }

    using (var memoryStream = new MemoryStream())
    {
        await file.CopyToAsync(memoryStream).ConfigureAwait(false);

        using (var package = new ExcelPackage(memoryStream))
        {
            var worksheet = package.Workbook.Worksheets[1]; // Tip: To access the first worksheet, try index 1, not 0
            var retVal= saveExcelPackageToDB(package,worksheet);
            return Content(retVal.ToString());
        }
    }

}

private async Task<string>  saveExcelPackageToDB(ExcelPackage package, ExcelWorksheet worksheet)
{
    var rowCount = worksheet.Dimension?.Rows;
    var colCount = worksheet.Dimension?.Columns;

    var sb = new StringBuilder();

    var d =new Device();

    var devices =new List<Device>();
    for(int row = 2; row <= rowCount.Value; row++)
    {

        d.Id=row.ToString();
        d.DeviceId=worksheet.Cells[row, 1].Value.ToString();
        d.DeviceSimpleName=worksheet.Cells[row, 2].Value.ToString();
        d.DeviceFriendlyName=worksheet.Cells[row, 3].Value.ToString();
        d.DeviceTimeZone=worksheet.Cells[row, 4].Value.ToString();
        d.DeviceFullTopic=worksheet.Cells[row, 5].Value.ToString();
        d.ModelNumber=worksheet.Cells[row, 6].Value.ToString();
        d.ManufacturerName=worksheet.Cells[row, 7].Value.ToString();
        devices.Add(d);


    }


    await  _repo.RegisterMultipleDevice(devices);

    return "Saved Successfully";
}
}

// Device Repository.cs

public async Task RegisterMultipleDevice(IEnumerable devices)
{

    await _dbContext.Devices.InsertManyAsync(devices);
}
 
Last edited by a moderator:
Did you debug your code? A NullReferenceException is generally very easy to diagnose. If that line is throwing the exception then there's only one reference that could possibly be the issue. You should debug and check whether _repo is null and fix that if it is.
 
Hi,

i don't see where you injected "_repo" or "_dbContext".

How is _repo injected or initilized ?
Forgotten to add the service for _repo or to inject it in constructor or method?

Best regards
 
Back
Top Bottom