28

I am trying to create database using Code First approach. When I run the following code I am getting the following exception. Is there anything wrong in the fields that I defined? How can we overcome this?

Exception:

An error occurred while updating the entries. See the inner exception for details.

Inner Exception:

"Invalid object name 'dbo.Dinners'.

Note: I do not have such a table (Dinners) in the database. The code is supposed to create the tables. I just gave connection string to identify the server as mentioned in EF Code First: Cannot connect to SQL Server. Should I change the connection string?

Connections String:

string connectionstring = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";

The LibraryReservationSystem database is already existing database. It has no tables. I am expecting EF to create the tables.

The connection string I copied from a working LINQ 2 SQL application. Do I need to make any changes to it to supply to EF?

enter image description here

UPDATE

When I included the following code, the exception got changed. Now it says - "Invalid object name 'dbo.Dinner'.". It is now complaining about Dinner table; not Dinners table.

    protected override void OnModelCreating(DbModelBuilder modelbuilder)
    {
        modelbuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }

Original CODE

    static void Main(string[] args)
    {

        string connectionstring = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";

        using (var db = new NerdDinners(connectionstring))
        {
            var product = new Dinner { DinnerID = 1, Title = 101 };
            db.Dinners.Add(product);
            int recordsAffected = db.SaveChanges();
        }

    }


using System.Data.Entity;
namespace LijosEF
{
public class Dinner
{
    public int DinnerID { get; set; }
    public int Title { get; set; }

}

public class RSVP
{
    public int RSVPID { get; set; }
    public int DinnerID { get; set; }

    public virtual Dinner Dinner { get; set; }
}

//System.Data.Entity.DbContext is from EntityFramework.dll
public class NerdDinners : System.Data.Entity.DbContext
{

    public NerdDinners(string connString): base(connString)
    { 

    }

    public DbSet<Dinner> Dinners { get; set; }
    public DbSet<RSVP> RSVPs { get; set; }
}
}

REFERENCE

  1. http://nerddinner.codeplex.com/discussions/358197
  2. Entity framework - Invalid Object Name
  3. Invalid object name 'dbo.TableName' when retrieving data from generated table
  4. http://blogs.msdn.com/b/adonet/archive/2011/09/28/ef-4-2-code-first-walkthrough.aspx
InteXX
  • 6,135
  • 6
  • 43
  • 80
LCJ
  • 22,196
  • 67
  • 260
  • 418

6 Answers6

29

The LibraryReservationSystem database is already existing database. It has no tables. I am expecting EF to create the tables.

That's not correct. If the database exists EF doesn't create any tables in this database. EF can create the database if it doesn't exist. That is the default database initializer CreateDatabaseIfNotExists that gets applied if you don't change it explicitly. You can select two other initializers: DropCreateDatabaseAlways or DropCreateDatabaseIfModelChanges. But neither of those will only create tables in an existing database but instead delete the database completely and create it from scratch including all tables.

What can you do:

  • Either delete the database manually (in SSMS for example), then EF will create a new one including the tables
  • Or use the DropCreateDatabaseAlways initializer once to let EF create the database including the tables, then remove the initializer again
  • Or if you can't delete the database for whatever reason write SQL code in the Seed method that adds the tables to the database (Wrong, thanks to Mark Stafford's comment)
  • Or use Code-First Migrations (EF >= 4.3) to add new tables to an existing database when you have added new entities.
Slauma
  • 175,098
  • 59
  • 401
  • 420
  • 1
    The seed method only gets called when the database is created, so that won't really help you. The database initializer is the right way to go, though. – Mark Stafford - MSFT Jul 23 '12 at 15:51
  • Thanks. It worked when I changed the connection string. Used a new database name. string connectionstring = "Data Source=.;Initial Catalog=NerdDinners;Integrated Security=True;Connect Timeout=30"; – LCJ Jul 24 '12 at 06:09
5

@Slauma's answer is the right one - the tables are created upon initialization. It's probably easiest to just delete the database and let EF create it (if you leave your connection string as is, it will create a database called LibraryReservationSystem on the local machine; you should probably specify an explicit host name if you're going to use the connection string in the config at this point).

You would need something along the lines of:

public class NerdDinnersInitializer : DropCreateDatabaseIfModelChanges<NerdDinners> { }

And you would also need to set the initializer in your Main method:

Database.SetInitializer(new NerdDinnersInitializer());

Word to the wise: NEVER deploy an application with an initializer like the one above. You can see this blog post about how to control initializers via the config file for more details on how to control this in production applications.

Mark Stafford - MSFT
  • 4,306
  • 3
  • 17
  • 23
2

I've just ran into the exact same issue - I'd already created my database on a development SQL box inside our network that needs SQL authentication.

When I ran my app, no tables were created. I found this awesome but simple article about creating a Code First Database Initializer Strategy which first checks to see if the database exists and then runs a script against the database to create the tables.

As stated in the article - pay attention that when such a strategy is deployed, whenever the application starts over, all the database tables will be recreated! This strategy should only run once.

But you already knew that.

Brett
  • 1,923
  • 3
  • 18
  • 24
0

As the error suggests, you do not have a table called Dinners within your database.

Are you using Single or Plural table names? i.e. Dinner or Dinners?

Gavin
  • 6,284
  • 5
  • 30
  • 38
  • I do not have such a table in databse. The code is supposed to create a database. I just gave connection string to identify the server. Should I change the connection string? – LCJ Jul 20 '12 at 14:16
  • In your web.config, do you have the connection string setup and pointing to an SQL Express/CE database? Do you even have SQL Express setup? – Gavin Jul 20 '12 at 14:20
  • I do not have any config file. I have a working SQL Server instance. It has other databases. – LCJ Jul 20 '12 at 14:22
  • See under "Configuring our Database Connection String" on http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx – Gavin Jul 20 '12 at 14:24
  • I am using an approach that does not use config file. – LCJ Jul 22 '12 at 11:55
  • As Gavin said, you don't have a table in database. Are you sure that your connection string is right ? – AechoLiu Jul 23 '12 at 06:10
  • @Toro I have already told that in my question. I am expecting the EF to create the table for me. – LCJ Jul 23 '12 at 06:29
  • If your connection string is wrong, the EF doesn't create any table for you. Because of this reason, is your connection string right ? – AechoLiu Jul 23 '12 at 06:45
  • @Toro. My connection string I copied from a working LINQ 2 SQL application. Do I need to make any changes on it to supply to EF? – LCJ Jul 23 '12 at 06:48
  • 1
    From what I understand, you can only create the database schema within the Application_Start of your Global.asax. If you were to create the schema on first access (i.e. your sample) it would cause your site to slow right down as it creates the schema. Also, as pointed out in the Link I provided, you have to provide a path to the database to access or be created, otherwise it doesn't know where to look. – Gavin Jul 23 '12 at 07:06
0

As I understood, you are expecting the code to create DB automatically based on your entities description. But this will not happen unless you create DB explicitly. Please check the following link http://www.simple-talk.com/dotnet/.net-framework/entity-framework-4460---learn-to-create-databases-from-the-model/ and this tutorial on EF codefirst: http://codefirst.codeplex.com/

Sasha
  • 8,537
  • 4
  • 49
  • 76
0

Once you have your entities designed you can right-click the workspace of the EDMX file and select 'Generate Database from Model...'. Click through until you have a script in your window. For that script you will have to remove DB creation step (if it is there) and go straight for CREATE TABLE ...

Copy-Paste and execute in whatever DB you've got. You might have to adjust the script for a specific RDBMS.

Renats Stozkovs
  • 2,549
  • 10
  • 22
  • 26