![](/img/trans.png)
[英]Entity Framework 6.1.3 when dbContext disposed detached objects are 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();
}
}
所以“表示层”调用这个操作,我得到一个错误:
那是因为_context.set()
操作如您所见是 null,但为什么是 null,我错过了什么吗?
我对其他数据库列的操作完全相同,并且效果很好。
直接投资配置:
实体属性不允许 null,您应该删除数据库字段中允许 null 的值还是添加? (空运算符)在 model
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.