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?
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
- http://nerddinner.codeplex.com/discussions/358197
- Entity framework - Invalid Object Name
- Invalid object name 'dbo.TableName' when retrieving data from generated table
- http://blogs.msdn.com/b/adonet/archive/2011/09/28/ef-4-2-code-first-walkthrough.aspx
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…