How to add new table to existing database code first

ef-code-first entity-framework

Question

Originally I used EF 6 code first to create a new database and two new tables. The code is:

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

    public TestingContext()
        : base("Testing")
    {
        Database.SetInitializer<TestingContext>(new MigrateDatabaseToLatestVersion<TestingContext, GenericIVR.Migrations.Configuration>());
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Attempt>().HasRequired(t => t.CallDataRecord).WithMany(a => a.Attempts).HasForeignKey(t => t.FKTaskId);

        modelBuilder.Entity<Attempt>().Property(x => x.AttemptId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();

        modelBuilder.Entity<CallDataRecord>().Property(x => x.TaskId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
    }
}

Now my strategy is changed, I don't want to a new DB. I want to add the new tables to an existing DB, say DevDB.

How to change the code? DO I have to use Reverse Engineering Code First?

UPDATED: The connection string is:

<connectionStrings>
<add name="Testing" connectionString="Data Source=dddd.corporate.xxxx.com; Initial Catalog=Testing; User ID=sa; Password=password; MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

1
33
5/15/2014 2:40:48 PM

Accepted Answer

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.

28
8/18/2014 3:14:00 PM

Popular Answer

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



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow