Question

I am trying to create MVC 4 application(OdeToFood tutorial) in VS Express. I have created this class in models.

But when I run the code, Database "OdeToFoodDB2" isn't being created

namespace OdeToFood.Models
{
    public class OdeToFoodDB2 : DbContext
    {
        public DbSet<Resturant> Resturant { get; set; }
        public DbSet<ResturantReview> ResturantReview { get; set; }
    }
}

In web.config file I have following connection string

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-OdeToFood-20140306003945;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-OdeToFood-20140306003945.mdf" providerName="System.Data.SqlClient" />

but this db doesn't contain the tables that I've specified in Model folder.

Was it helpful?

Solution

Make your class name same as connection string name. It will work.

<add name="OdeToFoodDB2" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-OdeToFood-20140306003945;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-OdeToFood-20140306003945.mdf" providerName="System.Data.SqlClient" />

Update:

There are multiple ways in which you can tell the DbContext how to use a database server:

1.) Assuming you have connection string same as above, keep the context class name same as connection string name.

public class OdeToFoodDB2 : DbContext
 {
 }

2.) Alternatively, you can specify the connection string in context base constructor:

public class MyContext : DbContext 
{ 
    public MyContext() 
        : base("OdeToFoodDB2") 
    { 
    } 
}

3.) Alternatively, you can also use the form “name=” for the string passed to the DbContext constructor. For example:

public class MyContext : DbContext 
{ 
    public MyContext() 
        : base("name=OdeToFoodDB2") 
    { 
    } 
}

OTHER TIPS

DbContext has a constructor overload that takes a connection string name.

You may also want to try adding new initializer to keep the database up to date

namespace OdeToFood.Models
{
    public class OdeToFoodDB2 : DbContext
        : base("DefaultConnection")
    {
        public DbSet<Resturant> Resturant { get; set; }
        public DbSet<ResturantReview> ResturantReview { get; set; }
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        var initializer = new MigrateDatabaseToLatestVersion<OdeToFoodDB2, Configuration>()
        Database.SetInitializer(initializer);
        base.OnModelCreating();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top