Search code examples
asp.net-coreentity-framework-coreef-code-firstentity-framework-migrations

How to create two table from one class by EF Core


I have a class for users :

public class users
{
    public int UserId { get; set; } 
    public string UserName { get; set; }
    // ....
}

I want to create a table called users. I write this line in AppDbContext.cs:

public Dbset<users> Users { get; set; }

it works correctly.

But when I add this line after the previous one:

public Dbset<users> UserChanges { get; set; }

no change happened in the migration file.

How I can have both users and userchanges tables in database, generated by EF Core with a code-first approach?


Solution

  • Yes, you can modify your UserChanges class to inherit from users.

    public class UserChanges : users
    {
        public DateTime ChangeDate { get; set; }
    }
    

    After that, you need to Update AppDbContext.

    public class AppDbContext : DbContext
    {
        public DbSet<users> Users { get; set; }
        public DbSet<UserChanges> UserChanges { get; set; }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<users>().ToTable("users");
            modelBuilder.Entity<UserChanges>().ToTable("userchanges");
        }
    }