簡體   English   中英

DbContext在Entity Framework中是null

[英]DbContext is null in Entity Framework

首先,當我嘗試從該列訪問數據時出現錯誤,我不知道是什么原因。

我正在使用 .NET 6 和 EF Core。

我有這個 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; }
}

SQL 服務器中的表:

在此處輸入圖像描述

dbcontext這種方式使用 Class 實體:

namespace Infrastructure.Data;

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

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

通過依賴注入,我將dbcontext注入到這個實現 crud 通用操作的 class 中:

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();
    }
}

所以“表示層”調用這個操作,我得到一個錯誤:

錯誤標題 E

那是因為_context.set()操作如您所見是 null,但為什么是 null,我錯過了什么嗎?

我對其他數據庫列的操作完全相同,並且效果很好。

直接投資配置:

在此處輸入圖像描述

實體屬性不允許 null,您應該刪除數據庫字段中允許 null 的值還是添加? (空運算符)在 model

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM