Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

entity framework - How to add new table to existing database code first

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" />

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...