Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq "Object reference not set to an instance of an object." [duplicate]

Tags:

c#

null

linq

Am a little lost on this one. Getting the error Object reference not set to an instance of an object. on the line db.EntityRichContents.DeleteAllOnSubmit(q); at runtime. Project builds fine.

protected override void ControllerOnEntityDeleted(EntityObj forEntity, EntityDeletionController.DeletionAction newStatus)
{
    if (newStatus == EntityDeletionController.DeletionAction.HardDelete)
    {
        if(forEntity == null) throw new Exception();

        using (var db = new DBContext())
        {
            var q = db.EntityRichContents.Where(c => c.C3Entity == ForEntity.TypeID && c.C3EntityRecordID == ForEntity.ID);
            db.EntityRichContents.DeleteAllOnSubmit(q);
            db.SubmitChanges();
        }
    }
}

Checking q.Any() or q == null doesn't help in any way (q isn't null).

like image 600
Tom Gullen Avatar asked Jan 21 '26 17:01

Tom Gullen


1 Answers

I see there are two similar variables: one is ForEntity (possibly a class property property?) and the second being forEntity (method parameter). Is that a typo?

Either way, given that the Where method is enumerated lazily I would assume that one of the lambda parameters in (c => c.C3Entity == ForEntity.TypeID && c.C3EntityRecordID == ForEntity.ID) is null. Try adding null-checks for every parameter and/or property to avoid exceptions.

like image 100
zen Avatar answered Jan 24 '26 06:01

zen