The original problem is to release current db file, delete it and create new one, so database could be completely fresh and clean. Why do I get exception if (as i believe) file should be released when context is disposed?
UPDATE:
Indeed, GC solves the problem.
Now I get another problem which is not obvious to me either. I just disposed context, created new one and tables should've been lazily initialized. server.db
file is created but has no tables. Can someone explain please?
class Program
{
static void Main(string[] args)
{
var dbFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "server.db");
if (File.Exists(dbFilename))
File.Delete(dbFilename);
using (var ctx = new CustomContext())
{
ctx.Products.Add(new Product {Cost = 10});
ctx.SaveChanges();
}
// SOLUTION (1)
GC.Collect();
GC.WaitForPendingFinalizers();
if (File.Exists(dbFilename))
File.Delete(dbFilename); // (1) WinIOError : can't access file server.db
using (var ctx = new CustomContext())
{
ctx.Products.Add(new Product {Cost = 10});
ctx.SaveChanges(); // (2) no such table: Products
}
}
}
public class CustomContext : DbContext
{
public DbSet<Product> Products { get; set; }
public CustomContext() : base("ServerConnection")
{
}
// App.config contains:
// <connectionStrings>
// <add name="ServerConnection" connectionString="Data Source=|DataDirectory|\server.db" providerName="System.Data.SQLite" />
// </connectionStrings>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var dbInitializer = new SqliteCreateDatabaseIfNotExists<CustomContext>(modelBuilder);
Database.SetInitializer(dbInitializer);
}
}
public class Product
{
[Key]
public double Cost { get; set; }
}