Zabahey
Zabahey

Reputation: 328

Cannot Generate Database from Entity Framework 4.1 Codefirst With SQL Server 2005

I try to create database from entity framework code first follow with this tutorial

http://www.asp.net/mvc/tutorials/getting-started-with-mvc3-part4-cs

but I use SQL Server 2005 instead when SQLExpress but When I execute solution don't have anything create. What wrong with my code

This is my code.

Movie.cs

public class Movie
{
    public int ID { get; set; }
    public string Title { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string Genre { get; set; }
    public decimal Price { get; set; }
}

public class MovieDBContext : DbContext
{
    public DbSet<Movie> Movies { get; set; }
}

And this is my connection string in web.config

<add name="MovieDBContext" 
     connectionString="data source=...;Integrated Security=SSPI;initial catalog=MovieDB;User Id=...;Password=..."
     providerName="System.Data.SqlClient" />

What Wrong with my code? Why database wasn't created.

thank you every one to help me.

Upvotes: 1

Views: 3047

Answers (3)

b0rg
b0rg

Reputation: 1897

Here's mine. I'm forcing database init, then ditching the context, then I'm force seeding it. I couldn't get the default behaviour to work with both Oracle and SQL CE.

var initer = new PPContextInitializer();
Database.SetInitializer<MovieDBContext >(new DropCreateDatabaseIfModelChanges<MovieDBContext >());

using (var db = new MovieDBContext())
{
    db.Database.Initialize(true);
}

using (var db1 = new MovieDBContext())
{
    initer.Seed(db1);
}

Upvotes: 0

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

The database is not created until it is used for the first time. You must do any of following to trigger database creation:

  • Create instance of your context and retrieve or persist any data
  • Create instance of your context and call context.Database.CreateIfNotExists()
  • Create instance of your context and call context.Database.Initialize(false)
  • Create instance of your context and call context.Database.Create()

Upvotes: 3

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

Have you added initialize methid in application start in your Global.asax file

 Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MovieDBContext>());

Upvotes: 0

Related Questions