0

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?

1
  • 1
    Why do you want this? Please provide some background. Either way, EF maps classes to tables, not DbSet names. Commented Feb 26 at 8:44

2 Answers 2

3

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");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

you need to define a separate entity class for UserChanges, even if it shares similar properties.

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

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

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

2 Comments

It's OK, but my user class has over 80 property and may change over time, Isn't any way to use one class?? Can I create a separate class inherited from Users? public class UserChanges:users {};??
even if it shares similar properties -- Why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.