44

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

3 Answers3

43

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

ParPar
  • 7,355
  • 7
  • 43
  • 56
Anshul Nigam
  • 1,608
  • 1
  • 12
  • 26
  • 9
    In case it helps someone else, I'll mention my facepalm. Make sure you use a property, not a field. It will only work with the `{get; set;}` – Thomas Nov 10 '14 at 05:29
  • Ahah! The property vs. field got me. Thank you @Thomas! – N1njaB0b Mar 21 '16 at 19:07
  • Do you simply create a new class in the Model folder and then add that one line `public DbSet MyNewModels { get; set; }`? Because i tried but it didn't work. It gave error: The project '' failed to build. Do you why this happens to me? – Nurul Mar 02 '17 at 08:31
  • I tried but getting error An error occurred while calling method 'ConfigureServices' on startup class 'Startup'. Consider using IDbContextFactory to override the initialization of the DbContext at design-time. – Shalin Jirawla Sep 02 '17 at 12:40
  • If you are as new as me, you might like to know the class to add to if you followed Blazor tutorials is the one that looks like this: `public class ApplicationDbContext : ApiAuthorizationDbContext` – D. A. Jun 15 '20 at 06:17
33

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.

JsonStatham
  • 9,770
  • 27
  • 100
  • 181
  • 6
    To anyone trying to edit this post to include the Add-Migration step prior to the Update-Database command, note that I have answered this assuming automatic migrations are enabled, hence why I am not trying to manually scaffold this change. Scroll down to 'Your first automatic migration' http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-automatic-migrations-walkthrough.aspx – JsonStatham Dec 17 '15 at 18:29
  • I am doing the same except the point 2 where i dont want to configure anything extra. But I am getting an exception when running Update-Database. It is ........"System.Runtime.Serialization.SerializationException: Type is not resolved for member 'Npgsql.NpgsqlException,Npgsql, Version=2.2.4.3, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7'. at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate) ............ Type is not resolved for member 'Npgsql.NpgsqlException,Npgsql, Version=2.2.4.3, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7'." – vinmm Sep 04 '19 at 02:29
  • @vinmm looks like its some sort of issue with the NPGSQL assembly https://stackoverflow.com/questions/29852359/npgsql-cant-find-npgsqlexception-when-doing-migrations – JsonStatham Sep 04 '19 at 09:16
  • i have tried this approach but in the configuration file when i am using model properties it gives the following error: "UserAttachment" doesnot have a definition for "UserId" and no accessible extension method "UserId" aceepting a first argument of type "UserAttachment" could be found (are you missing using a directive or an assembly reference?). i dont know how to resolve this i have created my table by creating a class in model it has been created easily but when i try to add seed data using the mentioned method its showing the error. – Sadia Oct 24 '19 at 11:27
  • Does you UserAttachment model have a public UserId? – JsonStatham Oct 28 '19 at 08:39
  • I have followed this exact post step by step, and everytime it results in a StackOverflowException. I don't understand why my automatic migrations are always broke! – Jay Mason Mar 22 '21 at 15:00
0
  1. Enable-Migrations from package manager console first.

  2. Create Configurations Class like

    namespace Demo.Data.Configurations
    {
        public class DemoConnectionConfiguration : EntityTypeConfiguration<DemoConnection>
        {
            public DemoConnectionConfiguration()
            {
                ToTable("DemoConnection");
                HasKey(a => a.Id);
            }
        }
    }
    
  3. Add Dbset and Model Builder in Context.cs like

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new DemoConnectionConfiguration());
    
        base.OnModelCreating(modelBuilder);
    }
    
    
    public DbSet<DemoConnection> DemoConnection { get; set; }
    
  4. "Update-Database" from Package Manager Console.

Note : "Please select the right folder from Default Project Dropdown list"

Congratulation! Your DemoConnection Table is in Database now.

Maximilian Ast
  • 3,369
  • 12
  • 36
  • 47
  • 1
    Hi, it seems you have two accounts (https://stackoverflow.com/users/5772608/chetan-pandey and https://stackoverflow.com/users/6782677/chetan-pandey). If you want, you can merge the two accounts by following the steps at https://stackoverflow.com/help/merging-accounts – Matt Jun 06 '17 at 11:40