I have a very basic model class
class Student
{
public int StudentID { get; set; }
public string Ad { get; set; }
public string Soyad { get; set; }
}
and a very basic DbContext
class
class StudentContext: DbContext
{
public StudentContext() :base("StudentDB")
{
}
public DbSet<Student> Students { get; set; }
}
I've tried with both a console app and also an ASP.NET MVC 5 project. Neither worked :/
When I build and run the application no database gets created. When I examine, I realized that although I even passed a parameter for DB Name in the base constructor, no connection string is inserted into app.config
or web.config
.
The Entity Framework Nuget package was installed before each trial and EF worked fine for my previous database first projects. I have no idea why I can't create database at first run. I even tried to add following line in Main()
function of console project:
StudentContext ctx = new StudentContext();
ctx.Database.CreateIfNotExists();
Did not work :/
Where does it say that the DbContext(string) would create a connection string in app.config? The remarks section of the DbContext class describes the connection string. But is says nowhere that the DbContext class would adjust app.config.
Changing the app.config would be undesired behaviour. What if you want the same DbContext to control two similar databases, for instance to copy data from one database to the other?
To get the the connection string after creating a DbContext instance use:
dbContext.Database.Connection.ConnectionString;
If you want to write the connection string to the App.Config, I'd suggest you'll write an extension function for it:
static class DbContextExtensions
{
public static void SaveConnectionString (this DbContext dbContext)
{
string connectionString = dbContext.Database.Connection.ConnectionString;
SaveConnectionString(connectionString);
}
private static void SaveConnectionString(string connectionString)
{ // save the string where you want it, for instance app.config
// out of scope of this question
}
}
usage
using(var dbConext = new StudentContext("...");
{
dbContext.SaveConnectionString();
}