1

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.

2 Answers 2

6

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

2 Comments

@Awais: U r welcome. Don't forget to vote up. Cheers!
Nice, didn't realise that +1
1

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();
}

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.