jmk22 jmk22 - 1 month ago 13
ASP.NET (C#) Question

Entity Framework in Visual Studio: database is not created with DbContext base constructor

I'm brand new to Visual Studio and .NET, and I'm following this tutorial on Lynda (Code-first development with the Entity Framework) to create an ASP.NET MVC app where I should be able to add Tour objects to a database using a form.

I've created a class

MyDbContext
that inherits from
DbContext
.

I've added a base class constructor with the name of the database that needs to be created for this app when information is submitted from the form. I've also added a
DbSet
named
Tours
that holds the tour objects.

Here is that code, in MyDBContext.cs:

public class MyDBContext : DbContext
{
public MyDBContext() : base("ExploreCalifornia")
{

}

public DbSet<Tour> Tours { get; set; }
}


In the Tour Controller, I create an instance of
MyDbContext
named
db
:

private MyDBContext db = new MyDBContext();


I have a
Create
page that contains the form to add a new tour, and here is the POST route for this page:

[HttpPost]
public ActionResult Create(Tour tour)
{
try
{
db.Tours.Add(tour);
db.SaveChanges();

return RedirectToAction("Index");
}
catch
{
return View();
}
}


Following with the debugger, when I try to add a new tour, it skips over the
SaveChanges
line and goes directly into the catch block. No database is ever created, and nothing shows up under App_Data in the Solution Explorer.

The tutorial mentions that the database will be created using SQL Server Express LocalDB, but I don't see any reference to LocalDB in the Server Explorer. This is still new, so I'm a little lost on how to approach this.

Any ideas of what might be going wrong, or where to start looking?

Answer

Thing is, when you use DbContext's contructor with a string parameter, the parameter must be either 1. name of a connection string from your app.config or web.config in the form name=MyConnectionString. For instance, your config contains

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="MyConnectionString" connectionString="your str here" />
  </connectionStrings>
</configuration>

and you declare your context like this

public class MyDBContext : DbContext
{
    public MyDBContext() : base("name=MyConnectionString")
    {

    }

    public DbSet<Tour> Tours { get; set; }
}

or 2. direct connection string, like this

public class MyDBContext : DbContext
{
    public MyDBContext() : base("Server=(local), Database=MyDBName, User=blah-blah...")
    {

    }

    public DbSet<Tour> Tours { get; set; }
}

Please, take note that if you use a config file, it must be in your AppDomain directory (for exe it's its folder; for a web site it's the site's bin folder).

Comments