I solved the answer myself by defining the required column in model as non-nullable column in the database .
DbContext's DbSet Returning Null Exception
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.