Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
in Repository Pattern System.NullReferenceException
Delete Method

System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=Microsoft.EntityFrameworkCore
StackTrace:
at Microsoft.EntityFrameworkCore.Internal.EntityFinder`1.ValidateKeyPropertiesAndExtractCancellationToken(Object[] keyValues, Boolean async, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Internal.EntityFinder`1.Find(Object[] keyValues)
at BL.Repositories.BaseRepository`1.GetById(Nullable`1 id) in E:\Programming\Folder\SoqRepository\BL\Repositories\BaseRepository.cs:line 51

What I have tried:

Class from database
C#
using System;
using System.Collections.Generic;

namespace Sq.Models;

public partial class VwItem
{
    public string ItemName { get; set; } = null!;
    public decimal PurchasePrice { get; set; }
    public decimal SalesPrice { get; set; }
    public int CategoryId { get; set; }
    public string? ImageName { get; set; }
    public DateTime CreatedDate { get; set; }
    public string CreatedBy { get; set; } = null!;
    public int CurrentState { get; set; }
    public string? UpdatedBy { get; set; }
    public DateTime? UpdatedDate { get; set; }
    public string? Description { get; set; }
    public string? Gpu { get; set; }
    public string? HardDisk { get; set; }
    public int? ItemTypeId { get; set; }
    public string? Processor { get; set; }
    public int? RamSize { get; set; }
    public string? ScreenReslution { get; set; }
    public string? ScreenSize { get; set; }
    public string? Weight { get; set; }
    public int? OsId { get; set; }
    public string CategoryName { get; set; } = null!;
    public string ItemTypeName { get; set; } = null!;
    public string OsName { get; set; } = null!;
    public int ItemId { get; set; }
}

Class Interface
C#
using Sq.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Domain.Interfaces
{
    public interface IBaseRepository <t> where T : class
    {
        public IEnumerable<t>GetAll();
        public IEnumerable<t> GetAll(Func<t, bool=""> Condition);
        public T GetById(int? id);
        public void Delete(T Entity);
        public void ChangeState(int id);
    }
}

C#
using Domain.Interfaces;
using Sq.BL;
using Sq.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BL.Repositories
{
    public class BaseRepository<t> : IBaseRepository<t> where T : class
    {
        public LapShopContext LapShopContext;
        public BaseRepository(LapShopContext _LapShopContext)
        {
            LapShopContext = _LapShopContext ?? throw new ArgumentNullException(nameof(_LapShopContext));
        }

implement interface
C#
using Sq.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Domain.Interfaces
{
    public interface IBaseRepository <t> where T : class
    {
        public T GetById(int? id);
        public void Delete(T Entity);
    }
}
        public T GetById(int? id)
        {
            try
            {
                return LapShopContext.Set<t>().Find(id);
            }
            catch (Exception)
            {
                return null;
            }
        }

        public void Delete(T entity)
        {
            try
            {
                LapShopContext.Set<t>().Remove(entity);
                LapShopContext.SaveChanges();
            }
            catch (Exception)
            {
             return;
            }
        }

Controller
C#
public ActionResult Delete(int ItemId)
{
    if (ItemId == null)
    {

        return BadRequest("ItemId is null");
    }

    var Obj = baseRepository.GetById(ItemId);
    baseRepository.Delete(Obj);

    return RedirectToAction("List");
}
Posted
Updated 18-Dec-23 10:11am
v3

As the error message, the issue is in Delete method. The Delete method attempts to remove an entity from the context using LapShopContext.Set<t>().Remove(entity). However, the error you're encountering is a NullReferenceException, which suggests that the entity parameter is null. The problem might be occurring because the GetById method returns null when the specified id is not found, and you are not checking for null before calling Delete. you can modify the Controller code as below:
C#
public ActionResult Delete(int ItemId)
{
    if (ItemId == 0)
    {
        return BadRequest("ItemId is invalid");
    }
    var Obj = baseRepository.GetById(ItemId);
    if (Obj == null)
    {
        return NotFound($"Item with ID {ItemId} not found");
    }
    baseRepository.Delete(Obj);
    return RedirectToAction("List");
}
 
Share this answer
 
Comments
A Belal 18-Dec-23 16:28pm    
the same error

and
Notice
when i do breakPoint
and stop in every Line

the Code in this Line is appear as below

{
return LapShopContext.Set<t>().Find(id);
id = 0x00000094
}






in address bar https://localhost:7201/admin/item/Delete?ItemId=19

my page is
This page isn’t workingIf the problem continues, contact the site owner.
HTTP ERROR 400
A Belal 18-Dec-23 16:47pm    
i tried your code
and Error Here



public T GetById(int? id)
{
try
{
return LapShopContext.Set<t>().Find(id); => this Line

System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=Microsoft.EntityFrameworkCore
StackTrace:
at Microsoft.EntityFrameworkCore.Internal.EntityFinder`1.ValidateKeyPropertiesAndExtractCancellationToken(Object[] keyValues, Boolean async, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Internal.EntityFinder`1.Find(Object[] keyValues)
at BL.Repositories.BaseRepository`1.GetById(Nullable`1 id) in E:\Programming\Folder\SoqRepository\BL\Repositories\BaseRepository.cs:line 51




}
catch (Exception)
{
return null;
}
}
M Imran Ansari 18-Dec-23 18:15pm    
The issue seems to be related to the use of a nullable int? id in the GetById method. The Find method of DbContext does not accept nullable types for the key parameter. You need to ensure that you are passing a non-null value to the Find method.

You can modify your GetById method to handle the nullable id by converting it to a non-nullable int before passing it to the Find method. Here's an updated version of your GetById method:

public T GetById(int? id)
{
try
{
if (id.HasValue)
{
return LapShopContext.Set<t>().Find(id.Value);
}
else
{
return null;
}
}
catch (Exception)
{
return null;
}
}
A Belal 19-Dec-23 8:45am    
i make abreakPoint
and debug code

and Error in this Line below
public T GetById(int? id)
{
try
{
if (id.HasValue)
{
Error in this Line below
this :
return LapShopContext.Set<t>().Find(id.Value);


System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=Microsoft.EntityFrameworkCore
StackTrace:
at Microsoft.EntityFrameworkCore.Internal.EntityFinder`1.ValidateKeyPropertiesAndExtractCancellationToken(Object[] keyValues, Boolean async, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Internal.EntityFinder`1.Find(Object[] keyValues)
at BL.Repositories.BaseRepository`1.GetById(Nullable`1 id) in E:\Programming\على شاهين كورس\SoqRepository\BL\Repositories\BaseRepository.cs:line 53



}
else
{
return null;
}
}
catch (Exception)
{
return null;
}
}
Since your repository code is swallowing all exceptions - an extremely bad idea, by the way! - the only reason for a NullReferenceException would be that the baseRepository is null.

Check the constructor to make sure you've assigned the field correctly, and thrown an exception if the value you've assigned happens to be null:
C#
public YourControler(IBaseRepository<YourItem> baseRepository)
{
    this.baseRepository = baseRepository ?? throw new ArgumentNullException(nameof(baseRepository));
}


Also:
C#
public ActionResult Delete(int ItemId)
{
    if (ItemId == null)
An int can never be null. The compiler will generate a CS0472 warning on that line.
 
Share this answer
 
Comments
A Belal 19-Dec-23 12:54pm    
Notice
when i do breakPoint
and stop in every Line

the Code in this Line is appear as below

{
return LapShopContext.Set<t>().Find(id);
id = 0x00000094
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900