2

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; }
}
idementia
  • 851
  • 1
  • 6
  • 12
  • 2
    Have you looked at [this question](http://stackoverflow.com/q/8511901/325521) The accepted answer says that you have to call the Garbage collector's `GC.Collect();` explicitly, while down the line, another answer with lot of votes says that you have to call `GC.WaitForPendingFinalizers()` after `GC.Collect()`. Take a look at that question and you might be able to solve your issue. – Shiva Mar 25 '17 at 01:01
  • @Shiva thanks, it really solves the problem. Updated the post with another relevant problem. – idementia Mar 25 '17 at 01:52

0 Answers0