Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object Reference not set to instance of an object...but it is?

I'm having an issue with deleting an object now, earlier this week this code was working fine, but now I'm getting a null reference exception, even though the object I'm attempting to delete, and the instance of the entity framework are not null.

    MHNHubEntities _entities = new MHNHubEntities();

    // Get, GetList, Add, Save etc.

    public void Delete(PackageProduct packageProduct)
    {
        _entities.PackageProducts.DeleteObject(packageProduct);
    }

packageProduct is a valid packageProduct, and everything else but this delete works. Normally I wouldn't ask how to solve a null reference exception - because its fairly obvious, check for nulls. However - in this case I'm stumped, what was working yesterday suddenly isn't and this is whats throwing the exception. Any help would be appreciated, I've already confirmed there are no null objects involved when this exception is thrown.

edit

I don't want to rule out that something is null and causing this - because of the very nature of the exception being thrown. As per request, here is the stack trace:

   at MHNHub.Areas.Store.Controllers.SettingsController.DeletePackage(Int32 id, FormCollection collection) in C:\Users\Grahame\Desktop\Projects\MHN Hub\Visual Studio Project\MHNHub\MHNHub\Areas\Store\Controllers\SettingsController.cs:line 618
   at lambda_method(Closure , ControllerBase , Object[] )
   at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
   at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
   at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a()
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)

Heres my controller action:

  [HttpGet]
        public ActionResult DeletePackage(int id, FormCollection collection)
        {
            try
            {

                IPackageRepository packageRepository = new PackageRepository();
                var package = packageRepository.GetPackage(id);

                IPackageProductRepository packageProductRepository = new PackageProductRepository();
                var packageProducts = package.PackageProducts.ToList();

                foreach (var packageProduct in packageProducts)
                {
                    packageProductRepository.Delete(packageProduct);
                }

                packageRepository.Delete(package);
                packageRepository.Save();

                return Json(new { Success = "true" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                //return JSON with exception
                var result = new { Message = ex.Message, InnerException = ex.InnerException.ToString() };

                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }
like image 653
Grahame A Avatar asked Feb 08 '11 19:02

Grahame A


People also ask

How do I fix the object reference not set to an instance of an object?

To fix "Object reference not set to an instance of an object," you should try running Microsoft Visual Studio as an administrator. You can also try resetting the user data associated with your account or updating Microsoft Visual Studio to the latest version.

How do I fix this error object reference not set to an instance of an object in unity?

Common solution:Check if your variable is attached to the object in question (you can find more clues in the other error lines). You might destroy the object before you use it. Check if it's the case. You might start the coroutine before you define the variable.

How do I fix NullReferenceException in C#?

Solutions to fix the NullReferenceException To prevent the NullReferenceException exception, check whether the reference type parameters are null or not before accessing them. In the above example, if(cities == null) checks whether the cities object is null or not.


2 Answers

Well, if it's making it as far as this line:

_entities.PackageProducts.DeleteObject(packageProduct);

and assuming this isn't due to inlining of DeleteObject (i.e. the error actually being inside there) then there are only two possible causes of a NullReferenceException:

  • _entities being null
  • _entities.PackageProducts being null

If this happens reproducibly, it should be easy to find out which it is:

public void Delete(PackageProduct packageProduct)
{
    var x = _entities;
    if (x == null)
    {
        throw new Exception("_entities was null");
    }
    var y = x.PackageProducts;
    if (y == null)
    {
        throw new Exception("_entities.PackageProducts was null");
    }
    y.DeleteObject(packageProduct);
}

(Just for the purposes of diagnosis, of course.)

like image 99
Jon Skeet Avatar answered Oct 21 '22 03:10

Jon Skeet


I've figured it out - thanks for everyone's time. The stack trace revealed I was looking at the wrong exception:

Line 618: var result = new { Message = ex.Message, InnerException = ex.InnerException.ToString() };

the null reference was coming from the InnerException being null. The real exception was:

base {System.SystemException} = {"The object cannot be deleted because it was not found in the ObjectStateManager."}

Which was solved by changing how I got the list of packageProducts, originally like this:

 IPackageRepository packageRepository = new PackageRepository();
 var package = packageRepository.GetPackage(id);

 IPackageProductRepository packageProductRepository = new PackageProductRepository();
 var packageProducts = package.PackageProducts.ToList();

And this is how it is now:

 IPackageProductRepository packageProductRepository = new PackageProductRepository();
 var packageProducts = packageProductRepository.GetPackageProducts().Where(p=>p.PackageId == package.PackageId).ToList();

And it's working!

But thanks for everything - I learned some new tricks for debugging :D!

like image 31
Grahame A Avatar answered Oct 21 '22 02:10

Grahame A