Data is Null. This method or property cannot be called on Null values. Entity Framework core

I tried to get the list of data but I am getting null from GetAllList() method. In this project I am using .Net core with ORM Entity Framework core code first approach with repository pattern

Entity class

public class SIDGenerator
{
    public int Id { get; set; }
    public string TrackId { get; set; }
    public string Track { get; set; }
    public string SId { get; set; }
    public int InstanceNumber { get; set; }
    public string Comment { get; set; }
    public bool InUse { get; set; }
    public bool IsOtherSysType { get; set; }
    public bool IsDeployed { get; set; }
    public string Exception { get; set; }
   
    public DateTime ReservationDate { get; set; }
    public DateTime LastUpdated { get; set; }
    public bool IsDeleted { get; set; }
    public bool IsManuallyDefined { get; set; }
    public int ReservatedBy { get; set; }
}

Interface

public interface ISidGeneratorRepository<T> where T :SIDGenerator
{
    T GetById(int id);

    /// <returns>List of the entity</returns>
    List<T> GetAllList();
}

Implementation

public class SidGeneratorRepository<T> : ISidGeneratorRepository<T> where T : SIDGenerator
{
    private readonly SHIELDDbContext _dbContext;
    private readonly ILoggerManager _logger;
    private readonly IDateTime _date;
    public SidGeneratorRepository(SHIELDDbContext dbContext, ILoggerManager logger, IDateTime date)
    {
        _dbContext = dbContext;
        _logger = logger;
        _date = date;
    }
 
    public void Delete(SIDGenerator entity)
    {
        throw new NotImplementedException();
    }

    public void DeleteById(int id)
    {
        throw new NotImplementedException();
    }

    public List<T> GetAllList()
    {
        var result= _dbContext.Set<T>()//This statement causes exception data is null
               .ToList();
        return result;
    }

    public T GetById(int id)
    {
        var sid = _dbContext.Set<T>()
                    .FirstOrDefault(i => i.Id == id);
        if (sid == null)
        {
            throw new NotFoundException("Sid could not be found with id " + id.ToString(), id);
        }

        return sid;
    }
}

This is my dbcontext class

public class SHIELDDbContext : DbContext
{
    public SHIELDDbContext(DbContextOptions<SHIELDDbContext> options)
        : base(options)
    {
    }

    public DbSet<SIDGenerator> SIDGenerator { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(UserRoleSeedConfig).Assembly);
    }
}

Below is my handler class

public Task<GetAllSidViewModel> Handle(GetAllSidQuery request, CancellationToken cancellationToken)
{
    try
    {
        
        var sidList = _sidRepository.GetAllList();
        if (sidList?.Count > 0)
        {
            var viewModel = new GetAllSidViewModel
            {
                sIDlist = sidList
            };
            return Task.FromResult(viewModel);
        }

        return null;
    }
    catch (Exception ex)
    {
        _logger.LogError("Could not retrieve SID LIST from DB" + ex);
        return null;
    }
}

Below is the table script for the above Entity

CREATE TABLE [dbo].[SIDGenerator](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Track] [nvarchar](max) NULL,
    [TrackId] [nvarchar](max) NULL,
    [SId] [nvarchar](max) NULL,
    [InstanceNumber] [int] NULL,
    [Comment] [nvarchar](max) NULL,
    [InUse] [bit] NULL,
    [IsOtherSysType] [bit] NULL,
    [IsDeployed] [bit] NULL,
    [Exception] [nvarchar](max) NULL,
    [ReservationDate] [datetime2](7) NULL,
    [LastUpdated] [datetime2](7) NULL,
    [ReservatedBy] [int] NULL,
    [IsDeleted] [bit] NULL,
    [IsManuallyDefined] [bit] NULL,
    CONSTRAINT [PK_SIDGenerators] PRIMARY KEY CLUSTERED 
    (
        [Id] ASC
    ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Change your model like this, or configure nullable properties by your wish.

public class SIDGenerator
{
    public int Id { get; set; }
    public string TrackId { get; set; }
    public string Track { get; set; }
    public string SId { get; set; }
    public int? InstanceNumber { get; set; }
    public string Comment { get; set; }
    public bool? InUse { get; set; }
    public bool? IsOtherSysType { get; set; }
    public bool? IsDeployed { get; set; }
    public string Exception { get; set; }
   
    public DateTime? ReservationDate { get; set; }
    public DateTime? LastUpdated { get; set; }
    public bool? IsDeleted { get; set; }
    public bool? IsManuallyDefined { get; set; }
    public int? ReservatedBy { get; set; }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x