Click here to Skip to main content
15,918,303 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I just created a simple class library using Code First Entity Framework 4.1.

The db connection is in the console applcations app.config and the name of the connectionstring is "default".
So i initialized the DbContext like this -
public class EmployeeContext : DbContext
       public EmployeeContext() : base("name=default") { }
        public List<employee> Employees { get; set; }

I have referenced the Class Library in the console application. Then just try to add one employee.
class Program
        static void Main(string[] args)
        static void createEmp()
            var obj = new EmployeeContext();
            Employee emp = new Employee();
            emp.ID = 1;
            emp.Name = "Test";

There is no error but the tables are not created in database.

When I look into the employeecontext, I see this exception -
ServerVersion '(((System.Data.Entity.DataContext)(obj)).Database.Connection).ServerVersion' threw an exception of type 'System.InvalidOperationException' string {System.InvalidOperationException}
The connection is closed

This is my first hands on with code first entity framework.

Anyone has any idea of what is wrong?
Updated 13-Dec-11 4:06am

1 solution

There are two big problems with your code. I highly recommend that you watch or read some intro material on using Code First and EF. On msdn ( you can find some short intro videos on code first.

Problem #1: in the dbcontext, Employees must be a DbSet<Employee> for EF to be able to interact with the employee data.

Problem #2:Code First will initialize the database the first time EF needs to access it. But there will be no db access because you've created the employee but the obj (context) is unaware of it.

Before obj.SaveChanges, add the new employee so that the obj is aware of it with:

Share this answer
Kochadayan 13-Dec-11 12:34pm    
Thanks for your response.After making the above changes and adding Database.SetInitializer(new DropCreateDatabaseIfModelChanges<employeecontext>());
the tables were created.
Member 14683067 11-Dec-19 2:47am    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900