DbContext's DbSet Returning Null Exception

Rashmi Gupta 96 Reputation points
2024-11-22T05:40:24.43+00:00

Facing an issue with accessing the DbSet of DbContext. When attempting to fetch values, an exception "Data is null" occurs, despite the table containing records in the database.

Details: DbContext Implementation:

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

    public DbSet<DbService> Services { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);         
    }
}

Registration in Program.cs:

string erp_SQL_ConnStr = builder.Configuration.GetValue<string>("ERP_SQL_ConnStr", Emp);
if (string.IsNullOrEmpty(erp_SQL_ConnStr))
    throw new InvalidOperationException("Connection string 'ERP_SQL_ConnStr' not found or is empty.");

builder.Services.AddDbContext<ErpSqlDbContext>(options => 
    options.UseSqlServer(erp_SQL_ConnStr, sqlOptions => 
        sqlOptions.EnableRetryOnFailure(maxRetryCount: 2, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null))
    .LogTo(Console.WriteLine, LogLevel.Error));

DbService Model:

namespace SqlIntegrationUI.Models.Domains
{
    [PrimaryKey(nameof(RecId))]
    public partial class DbService
    {
        private string ServiceName;
        private string ServiceTable;
        private string ServiceEndpoint;

        [Key]
        public long RecId { get; set; }

        [JsonProperty("Enable")]
        public bool Enable { get; set; } = true;

        [Required]
        [StringLength(255, ErrorMessage = "The service name has to be maximum of 255 characters")]
        [MinLength(3, ErrorMessage = "The service name has to be minimum of 3 characters")]
        [RegularExpression("^[a-zA-Z0-9\\s-_]*$")]
        [JsonProperty("Name")]
        public string Name
        {
            get => ServiceName;
            set
            {
                ServiceName = IsEmpty(value) ? Endpoint : value.Trim();
            }
        }

        // Other properties follow...
    }
}

Data Fetching:

public class ServiceRepository
{
    private readonly ErpSqlDbContext _context;

    public ServiceRepository(ErpSqlDbContext dbContext)
    {
        _context = dbContext;
        _context.Database.EnsureCreated();
    }

    public async Task<List<DbService>> GetAllAsync(string? sortBy = Emp, string? filterOn = Emp, string? filterQuery = Emp, bool ascending = true, int pageNo = 1, int pageSize = 100)
    {
        var services = await _context.Services.AsNoTracking().ToListAsync();
    }
}

Encountering the following error:

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

The database connection using the same connection string works fine with ADO.Net, and EFCore migrations have been applied successfully. All EFCore DLLs are at version 8.0.8, which should be compatible with .NET 8. The same code worked previously without issues but has stopped functioning without any changes made. Assistance in resolving this critical application issue would be appreciated.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
761 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,667 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,097 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Rashmi Gupta 96 Reputation points
    2024-11-22T07:03:59.43+00:00

    I solved the answer myself by defining the required column in model as non-nullable column in the database .

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.