'NET CORE API EF, Value cannot be null. (Parameter 'entity') when creates object instance

When I try to create a new instance of the object "DatosUbicacionUser" throws me this exception:

Value cannot be null. (Parameter 'entity')

this is the line that throws me the error

ui.Ubicacion = new DatosUbicacionUser();

this is my appDBContext

namespace Sporteate.API.Contexts
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, String>
    {
        IHubContext<Hubs.HubNotifications> _hubContext;

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {

        }
      
      ...DBSETS

        public DbSet<DatosUbicacionUser> DatosUbicacionesUser { get; set; }
      ...more DBSETS

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //UNIQUES
            

            base.OnModelCreating(modelBuilder);

            //Con IsDeleted

      
           ...
            modelBuilder.Entity<DatosUbicacionUser>().Property<bool>("isDeleted");
            modelBuilder.Entity<DatosUbicacionUser>().HasQueryFilter(m => EF.Property<bool>(m, "isDeleted") == false);
...Deleted") == false);

          ...

      
            modelBuilder.Entity<Gym>()
           .HasMany(bc => bc.Clientes);
           

            modelBuilder.Entity<ClientePlan>()
            .HasKey(bc => new { bc.ClienteId, bc.PlanId, bc.FechaCaducidad, bc.FechaBaja });

            modelBuilder.Entity<ClientePlan>()
            .HasKey(bc => new { bc.ClienteId, bc.PlanId, bc.FechaCaducidad, bc.FechaBaja });


        
        }

        public override int SaveChanges()
        {
            UpdateSoftDeleteStatuses();

            var c = cc();
            int ra = base.SaveChanges();

            if (ra > 0)
                nc(c);

            return ra;
        }

 
        public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default(CancellationToken))
        {
            UpdateSoftDeleteStatuses();
            return await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
        }

        private void UpdateSoftDeleteStatuses()
        {
            foreach (var entry in ChangeTracker.Entries())
            {

                try { 
                    switch (entry.State)
                    {

                        case EntityState.Added:
                            
                            entry.CurrentValues["isDeleted"] = false;
                            break;
                        case EntityState.Deleted:
                            entry.State = EntityState.Modified;
                            entry.CurrentValues["isDeleted"] = true;
                            entry.CurrentValues["FechaBaja"] = DateTime.Now;
                            break;
                        case EntityState.Modified:
                            entry.CurrentValues["isDeleted"] = false;
                            entry.CurrentValues["FechaBaja"] = null;
                            break;
                    }
                }
                catch (InvalidOperationException ex)
                {

                }
            }
        }

        void nc(Tracker data)
        {
            //foreach (var i in data.Deleteds)
            //    _hubContext.Clients.All.SendAsync(i.Key, "deleted", i.Value);

            //foreach (var i in data.Addeds)
            //    _hubContext.Clients.All.SendAsync(i.Key, "added", i.Value);

            //foreach (var i in data.Modifieds)
            //    _hubContext.Clients.All.SendAsync(i.Key, "modified", i.Value);
        }

       
    }
}

this is my startup file.


[assembly: ApiConventionType(typeof(DefaultApiConventions))]
namespace Sporteate.API
{
    public class Startup
    {

        private static readonly ILog log = LogManager.GetLogger(typeof(Startup));
        public Startup(IConfiguration configuration)
        {
            try
            {
                Configuration = configuration;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }


        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            try
            {

                services.AddCors(options =>
                {
                    options.AddPolicy("PermitirApiRequest",
                        builder => builder.AllowAnyOrigin()
                        .AllowAnyMethod().AllowAnyHeader());
                });
                //services.AddScoped<HashService>();
                //services.AddDataProtection();
                services.AddControllersWithViews()
                    .AddNewtonsoftJson(options =>
                    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                );

                services.AddSignalR();

                services.AddResponseCaching();
                services.AddAutoMapper(options =>
                {
                              here commes the automapper settings

                }, typeof(Startup));
                services.AddScoped<MiFiltroDeAccion>();
                services.AddDbContext<ApplicationDbContext>(options => {
                    options.UseSqlServer(Configuration.GetConnectionString("defaultConnection"));

                });
                services.AddTransient<ApplicationDbContext>();
                services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
                {
                    options.Lockout.MaxFailedAccessAttempts = 3;
                    options.Password.RequireNonAlphanumeric = false;
                    options.SignIn.RequireConfirmedEmail = false;
                    options.User.RequireUniqueEmail = true;
                })
                    //Author: Damian Zmijanovich
                    //Descripcion: Se agrega para devolver erorres custom en español
                    .AddErrorDescriber<LocalizedIdentityErrorDescriber>()
                      //.AddUserStore<ApplicationDbContext>()
                      .AddEntityFrameworkStores<ApplicationDbContext>()
                    .AddDefaultUI()
                    .AddDefaultTokenProviders();
                services.AddMvc(options =>
                {
                    options.Filters.Add(new FiltroExcepcion());
                    
                }).SetCompatibilityVersion(CompatibilityVersion.Latest);
              
                services.AddSingleton<IActionContextAccessor, ActionContextAccessor>()
                    .AddScoped<IUrlHelper>(x => x
                        .GetRequiredService<IUrlHelperFactory>()
                            .GetUrlHelper(x.GetRequiredService<IActionContextAccessor>().ActionContext));

                services.AddHttpContextAccessor();
                services.AddSingleton<IAlmacenadorArchivos, AlmacenadorArchivosLocal>();

                services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddJwtBearer(options =>
                     options.TokenValidationParameters = new TokenValidationParameters
                     {
                         ValidateIssuer = false,
                         ValidateAudience = false,
                         ValidateLifetime = true,
                         ValidateIssuerSigningKey = true,
                         IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(Configuration["jwt:key"])),
                         ClockSkew = TimeSpan.Zero
                     });
                try
                {
                    services.Configure<EmailSettings>(Configuration);
                    services.AddTransient<IEmailSender, EmailSender>();
                    services.AddTransient<FuncionesComunes>();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseStaticFiles();
            app.UseRouting();
            //app.UseHttpsRedirection();
            app.UseAuthentication();
            app.UseResponseCaching();
            app.UseCors();
            app.UseStaticFiles();
            app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
        

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                string swaggerJsonBasePath = string.IsNullOrWhiteSpace(c.RoutePrefix) ? "." : "..";
                c.SwaggerEndpoint($"{swaggerJsonBasePath}/swagger/v1/swagger.json", "Sporteate_API");

            });
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<HubNotifications>("/notifications");
            });
        }
    }
}

The database table is already created. I can't avoid the error and I don't understand why is throwing this.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source