I'm trying to add a new connection to database in an ASP.NET application, and I'm trying to use code-first initialization.
For now, that are my connection strings:
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Auth-20211221042302.mdf;Initial Catalog=aspnet-Auth-20211221042302;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="DriveMeConnection"
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\DriveMe-App-20211231001122.mdf;Initial Catalog=DriveMe-App-20211231001122;Integrated Security=True;MultipleActiveResultSets=True;App=EntityFramework"
providerName="System.Data.SqlClient" />
</connectionStrings>
The first, DefaultConnection
, was generated for the ASP.NET authentication, and works well.
The second, DriveMeConnection
, is the database I want to create from my code-first model.
So, I created a new DbContext
as usual:
public class DatabaseContext : DbContext
{
public DbSet<Azienda> Aziende;
public DbSet<ClientePrivato> ClientiPrivati;
public DbSet<Fornitore> Fornitori;
public DbSet<Auto> ParkAuto;
public DbSet<Guidatore> Guidatori;
public DbSet<Pratica> Pratiche;
public DatabaseContext() : base("name=DriveMeConnection")
{
}
}
(there's no difference if I use base("name=DriveMeConnection")
or base("DriveMeConnection")
).
When I am trying to read something, for example
using (DatabaseContext db = new DatabaseContext())
{
List<Fornitore> lst = db.Fornitori.ToList();
}
Fornitori
table was not created. In this case, the whole database wasn't created.
I tried to add
Database.SetInitializer<DatabaseContext>(new CreateDatabaseIfNotExists<DatabaseContext>());
inside the DatabaseContext
constructor, but nothing changes.
I tried to add
this.Database.CreateIfNotExists();
inside the DatabaseContext
constructor, the database was created, but the tables aren't there.
I tried to force initialization with:
using (DatabaseContext db = new DatabaseContext())
{
db.Database.Initialize(force: true);
}
This creates the database, but it is still empty without tables.
What did I miss?
I finally solved, without migrations that I don't need for now, I only call this function at startup.
public static void FirstConfiguration()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DatabaseContext>());
var context = new DatabaseContext();
context.Database.Initialize(true);
}
And in the DbContext, the dataset need to be properties with the get and set method:
public class DatabaseContext : DbContext
{
public DbSet<Azienda> Aziende { get; set; }
public DbSet<ClientePrivato> ClientiPrivati { get; set; }
public DbSet<Fornitore> Fornitori { get; set; }
public DbSet<Auto> ParkAuto { get; set; }
public DbSet<Guidatore> Guidatori { get; set; }
public DbSet<Pratica> Pratiche { get; set; }
public DatabaseContext() : base("name=DriveMeConnection")
{
}
}