Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new table to existing database code first

People also ask

How will you add a new table to an existing database code first in .NET core?

EF Code First with existing database on another database This is what to do:...1 - Add migrations to your DEV environment and set your database initializer to ... MigrateDatabaseToLatestVersion.... Another option is to ... programatically run migrations....... enabl...


Just create your new table as a model and add its entry in DbContext class

something like

 public class TestingContext : DbContext, IDisposable
{
    public DbSet<CallDataRecord> CallDataRecords { get; set; }
    public DbSet<Attempt> Attempts { get; set; }

    public DbSet<MyNewModel> MyNewModels { get; set; }

Then add-migration and update-database


If you have automatic migrations set up this should be pretty straight forward.

If you haven't, you will need to run Enable-Migrations –EnableAutomaticMigrations Perhaps do some further reading here first though: http://msdn.microsoft.com/en-gb/data/jj554735.aspx

For anyone looking to update a database with a new table (say I want to add an UserAttachment table to sit alongside my existing User table) using EF code first, do the following:

With automatic migrations enabled you should ensure you have...

1.) Create your new model as you see fit.

2.) Create your Configuration file, something along the lines of:

 class UserAttachmentConfiguration : EntityTypeConfiguration<UserAttachment>
    {
        public UserAttachmentConfiguration()
            : base()
        {
            HasKey(p => p.UserId);
            ToTable("UserAttachment");    

            HasRequired(t => t.User)
                .WithOptional(t => t.UserAttachment);                
        }
    }

3.) Add your DbSet and modelBuilder data in your main Context.cs file

DbSet

public DbSet<UserAttachment> UserAttachment {get; set;}

modelBuilder

modelBuilder.Configurations.Add(new UserAttachmentConfiguration());

4.) Run update-database via Visual Studio's Package Manager Console, make sure you have selected the correct project from the drop down, this is likely to be a .Repository named project.

Your new table should now exist in your database.