Nistor Alexandru
Nistor Alexandru

Reputation: 5393

Entity Framework Code First db tables don't generate on existing db

Hi I am using Entity framework code first for the first time and I am having trouble generating the tables.I have created an empty database in my App_Data in an MVC3 application. This are the models I have created:

 public class Brand {
    public int BrandId { get;set; }
    public string BrandName { get;set; }
}

public class Model
{
    public int ModelId { get;set; }
    public Brand BrandId { get;set; }
    public Category CategoryId { get;set; }
    public string ModelName { get;set; }
}

public class Category
{
    public int CategoryId { get;set; }
    public string CategoryName { get;set; }
}

This is the dbContext:

public class CarsEntities : DbContext{
    public DbSet<Brand> Brands { get;set; }
    public DbSet<Model> Models { get;set; }
    public DbSet<Category> Categories {get;set;} 
}

And this is the connectionString in web.config:

<connectionStrings>
      <add name="CarsEntities" connectionString="Data Source='D:\Projects IDE\Visual Studio\MyWork\Websites\SellCars\SellCars\App_Data\Cars.sdf'" providerName="System.Data.SqlClient" />      
 </connectionStrings>

Now I have initialized CarsEntities in my HomeController but it seems that none of the tables get generated.What am I doing wrong?

Upvotes: 1

Views: 257

Answers (2)

levelnis
levelnis

Reputation: 7705

First up - since you're using SQL Server Compact, you need to change the provider name to use Compact rather than SQL Server:

<add name="CarsEntities" connectionString="Data Source='D:\Projects IDE\Visual Studio\MyWork\Websites\SellCars\SellCars\App_Data\Cars.sdf'" providerName="System.Data.SqlServerCe.4.0" />

Next, you'll need to use a database initializer in your Application_Start code somewhere, which tells entity framework whether to create the database tables and how often to recreate them. See here:

http://www.codeguru.com/csharp/article.php/c19999/Understanding-Database-Initializers-in-Entity-Framework-Code-First.htm

http://msdn.microsoft.com/en-us/data/jj591621.aspx

Upvotes: 1

COLD TOLD
COLD TOLD

Reputation: 13599

I think the problem comes in your

webcofig 

here is if you want to use the db as a file like mdf file database file specifically in dtasource

       `<add name="CarsEntities"  connectionString="data source=.\SQLEXPRESS; Integrated
 Security=SSPI;AttachDBFilename=|yourDirectoryDirectory|\thenameofyourdb.mdf;User
 Instance=true"  providerName="System.Data.SqlClient" /`>

Upvotes: 1

Related Questions