1

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?

2 Answers 2

1

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" /`>
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.