Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...