'No tables generated using code-first in .NET Core

I am using VS 2016, SQL Server 2016, .NET Core, code-first, when I try to update the database, no table is generated.

Context:

public DataContext()
{
}

public DataContext(DbContextOptions<DataContext> options)
            : base(options)
{
}
                
public virtual DbSet<Relative> Relatives { get; set; }
public virtual DbSet<User> Users { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        optionsBuilder.UseSqlServer("Server=DESKTOP-ARVMMP2\\SQLEXPRESS;Database=PraxedesDb;Trusted_Connection=True");
    }
 }

 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
     modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");

     modelBuilder.Entity<Relative>(entity =>
            {
                entity.ToTable("Relatives");

                entity.Property(e => e.Id)
                    .ValueGeneratedNever()
                    .HasColumnName("Id");

                entity.Property(e => e.DateOfBirth).HasColumnType("DateOfBirth");
                entity.Property(e => e.RelativeNames).HasColumnName("RelativeNames");
                entity.Property(e => e.RelativeLastNames).HasColumnName("RelativeLastNames");                
                entity.Property(e => e.RelativeGender).HasColumnName("RelativeGender");
                entity.Property(e => e.RelativeDocumentNumber).HasColumnName("RelativeDocumentNumber");
                entity.Property(e => e.InLaw).HasColumnName("InLaw");
                entity.Property(e => e.RelativeAge).HasColumnName("RelativeAge");

                entity.Property(e => e.UserId).HasColumnName("UserId");

                entity.HasOne(d => d.User)
                    .WithMany(p => p.Relatives)
                    .HasForeignKey(d => d.UserId)
                    .HasConstraintName("UserId");
            });

    modelBuilder.Entity<User>(entity =>
            {
                entity.ToTable("Users");

                entity.Property(e => e.Id)
                    .ValueGeneratedNever()
                    .HasColumnName("Id");

                entity.Property(e => e.DateOfBirth).HasColumnType("DateOfBirth");
                entity.Property(e => e.UserNames).HasColumnName("UserNames");
                entity.Property(e => e.UserLastNames).HasColumnName("UserLastNames");
                entity.Property(e => e.UserPlatformName).HasColumnName("UserPlatformName");
                entity.Property(e => e.UserPassword).HasColumnName("UserPassword");
                entity.Property(e => e.UserGender).HasColumnName("UserGender");
                entity.Property(e => e.UserDocumentNumber).HasColumnName("UserDocumentNumber");                               
            });

    OnModelCreatingPartial(modelBuilder);
}

partial void OnModelCreatingPartial(ModelBuilder modelBuilder);

The models:

        public User()
        {
            Relatives = new HashSet<Relative>();
        }

        public int Id { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public string UserNames { get; set; }
        public string UserLastNames { get; set; }
        public string UserPlatformName { get; set; }
        public string UserPassword { get; set; }
        public string UserGender { get; set; }
        public int UserDocumentNumber { get; set; }

        public virtual ICollection<Relative> Relatives { get; set; }

    public class Relative
    {
        public int Id { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public string RelativeNames { get; set; }
        public string RelativeLastNames { get; set; }        
        public string RelativeGender { get; set; }
        public int RelativeDocumentNumber { get; set; }
        public string InLaw { get; set; }
        public int RelativeAge { get; set; }

        public int? UserId { get; set; }
        public virtual User User { get; set; }
    }

Startup:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

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)
{
    // for reference loop handling 
    services.AddControllers().AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });

    // for mySettingModel
    services.Configure<MySettingsModel>(Configuration.GetSection("MySettings"));

    // for Cors Allow
    services.AddCors();

    services.AddControllers();
    // services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));
    services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "PraxedesBackend", Version = "v1" });
            });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // for Cors Allow
    app.UseCors(options => options.WithOrigins("http://localhost:4200")
                .AllowAnyMethod()
                .AllowAnyHeader()
            );

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "PraxedesBackend v1"));
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
}

A user has many relatives, that is the relationship between the two models.

Is there a problem on the DataContext? or maybe the models? Can you please help me?

I tried with:

 modelBuilder.Entity<Relative>()
            .HasOne<User>(s => s.User)
            .WithMany(g => g.Relatives)
            .HasForeignKey(s => s.UserId);

With no result either.

I did the migration and the update-database commands



Solution 1:[1]

it's not enough create the classes and the dbcontext to create the database and the tables. You have to run two commands:

dotnet ef migrations add "create db and tables"
dotnet ef database update

Every time you change your models you have to run these 2 commands to reflect the changes to the database...

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 Michele Massari