Search code examples
c#linqasp.net-coreentity-framework-core

I get a null reference error on the line where I use Name


var category = await _companyContext.PRODUCTCATEGORIES.FirstOrDefaultAsync(p => p.ID == categoryId && (bool)p.STATE);

            category.NAME = name;
            category.WORKPLACEID = workplaceid;
            _companyContext.Update(category);

My problem is in the line with NAME


Solution

  • FirstOrDefaultAsync will return either an instance or null. Therefore, you should always check the return value for null e.g.,

    var category = await _companyContext.PRODUCTCATEGORIES.FirstOrDefaultAsync(p => p.ID == categoryId && (bool)p.STATE);
    
    if(category!=NULL)
    {
            category.NAME = name;
            category.WORKPLACEID = workplaceid;
            _companyContext.Update(category);
    }
    

    Without the full exception text being posted I suspect that category == NULL is true