46

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

4 Answers 4

44

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

Sign up to request clarification or add additional context in comments.

5 Comments

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;}
Ahah! The property vs. field got me. Thank you @Thomas!
Do you simply create a new class in the Model folder and then add that one line public DbSet<MyNewModel> 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?
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.
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<ApplicationUser>
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.

6 Comments

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' blogs.msdn.com/b/adonet/archive/2012/02/09/…
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 looks like its some sort of issue with the NPGSQL assembly stackoverflow.com/questions/29852359/…
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.
Does you UserAttachment model have a public UserId?
|
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.

1 Comment

Hi, it seems you have two accounts (stackoverflow.com/users/5772608/chetan-pandey and stackoverflow.com/users/6782677/chetan-pandey). If you want, you can merge the two accounts by following the steps at stackoverflow.com/help/merging-accounts
0

Use the below two commands.

add-migration Seed[Your Db Name]Tables update-database

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.