Home > Software design >  DbContext is null in Entity Framework
DbContext is null in Entity Framework

Time:03-28

First of all I get an error when I try to access the data from this column and I don't know what the reason is.

I'm working with .NET 6 and EF Core.

I have this class :

namespace Core.Entities;

public class Usuario 
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int IdTecnico { get; set; }
    public string Nombre { get; set; }
    public string Apellido1 { get; set; }
    public string Apellido2 { get; set; }
    public string NIF { get; set; }
    public string EmailPersonal { get; set; }
    public string EmailCorporativo { get; set; }
    public string Direccion { get; set; }
    public string Telefono1 { get; set; }
    public string Telefono2 { get; set; }
    public DateTime FechaRegistro { get; set; }
    public DateTime? FechaAltaEmpresa { get; set; }
    public DateTime? FechaBajaEmpresa { get; set; }
    public string WebContrasena { get; set; }
    public int WebRol { get; set; }
    public int SeguimientNotificacion { get; set; }
    public DateTime? SeguimientoFecha { get; set; }
    public int? SeguimientoIntervalo { get; set; }
    public decimal? EmpresaTarifa { get; set; }
    public int? EmpresaCategoria { get; set; }
    public string ClienteCuenta { get; set; }
    public int? ClienteCategoria { get; set; }
    public int? ClienteNivel { get; set; }
    public string RedmineAPIKey { get; set; }
    public int? RedmineIdProyecto { get; set; }
}

Table in SQL Server:

enter image description here

Class entity is used by this dbcontext this way:

namespace Infrastructure.Data;

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

    public DbSet<Core.Entities.Usuario> Usuarios { get; set; }
}

With dependency injection, I inject it the dbcontext into this class that implements generic operations of crud:

namespace Infrastructure.Repositories;

public class UsuarioRepository : IRepository<Core.Entities.Usuario, int> 
{
    UsuariosContext _context;

    public UsuarioRepository(UsuariosContext context) 
    {
        _context = context; 
    }

    public async Task<IReadOnlyList<Usuario>> GetAllAsync() 
    {
        // I get an error because _context.set() operation is null
        return await _context.Set<Usuario>().ToListAsync();
    }
}

So the "presentation layer" calls this operation and I get an error:

rror captionE

That's because _context.set() operation is null as you see, but why is null, did I miss something?

I am doing EXACTLY the same with other db columns and it works perfectly.

DI Config:

enter image description here

CodePudding user response:

Entity properties dont allow null, you should delete allow null values in fields in database or add ? (null operator) on model

  • Related