2

After MUCH research into Entity Framework (targeting DNX 4.5.1) I keep coming to the same conclusion that when using the code-first approach EF is supposed to create any tables that do not exist.

DbContext:

public class AccountReadContext : DbContext
    {
        public AccountReadContext(DbContextOptions options)
        : base(options)
        {}

        public DbSet<AccountRead> AccountReads { get; set; }  
    }

Database Provider:

public void AddAccountRead(AccountRead reads)
        {
            _dbContext.AccountReads.Add(reads);
            _dbContext.SaveChanges(); //System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'AccountRead'
        }

I know why this is happening (the table is missing). What I can't figure out is how do I get code-first to do its thing and create the table?

m.edmondson
  • 30,382
  • 27
  • 123
  • 206
  • http://stackoverflow.com/questions/11581147/entity-framework-exception-invalid-object-name – Nikhil Vartak May 18 '16 at 10:56
  • @Think2ceCode1ce - I followed the linked advice and renamed my database (so it doesn't exist) but I just get `SqlException (0x80131904): Cannot open database` – m.edmondson May 18 '16 at 11:08

3 Answers3

0

You have to enable code first migrations in your project. In the PowerShell window (package manage console) you issue the command:

Enable-Migrations

And then, every time you update your POCO objects, add new tables etc, you need to enter :

Add-Migration

Some documentation on this here: https://msdn.microsoft.com/en-us/data/jj591621.aspx

Pedro G. Dias
  • 3,162
  • 1
  • 18
  • 30
  • The term 'Enable-Migrations' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.At line:1 char:1 – m.edmondson May 18 '16 at 10:52
  • Hmm, that should work, are you using Visual Studio, did you type that into package manager console? And do check that the correct project is selected before you hit enter :) – Pedro G. Dias May 18 '16 at 11:11
  • Yes checked all of those, I'm starting tho think I don't have EF correctly installed – m.edmondson May 18 '16 at 11:20
0

Automatic Migrations should be enabled by default. If you disabled them (AutomaticMigrations = false), you should run Update-Database command manually, or set the Database Initializer to MigrateDatabaseToLatestVersion<,>

Ciprian Lipan
  • 340
  • 2
  • 9
0

In the end I had to use the EntityFramework commands in the project's root folder:

Update database:
dnx ef database update -c "AccountReadContext"

Add / Remove columns (specify column name):
dnx ef migrations add Reading -c "AccountReadContext"
dnx ef database update -c "AccountReadContext"

This provides a bit more info

m.edmondson
  • 30,382
  • 27
  • 123
  • 206