Home > database >  How can I make Entity Framework Core / SQLite commit all changes so I can archive the underlying fil
How can I make Entity Framework Core / SQLite commit all changes so I can archive the underlying fil

Time:09-28

I have a set of unit tests that uses SQLite and Entity Framework Core. Here's the first version, which I've reduced down to the essentials for the purpose of posting this question. The code is in two using blocks for reasons that should become clear.

/* Clear the files before starting. */
File.Delete("testdata.db");
File.Delete("copydata.db");

/* Create a fixed set of records suitable for unit testing. */
using (var db = new TestDataContext("testdata.db"))
{
  /* Create all the tables needed. */
  db.Database.EnsureCreated();

  /* Add several hundred fixed records that all unit tests use. */
  db.Add(new Person{Name="Bill", Vegetable="Rutabaga"});

  /* Save them all. */
  db.SaveChanges();
} /* Close connection. */

/* Open the file again. */
using (var db = new TestDataContext("testdata.db"))
{
  /* Read the first record of the many in the database. */
  Console.WriteLine(db.Persons.First().Name);
}

This works, but there's a problem. There are several (hundreds) unit tests that each call the same code to set up the database with several (hundreds) fixed records. This effort takes a lot of time. I'd like to instead squirrel away the database file that contains that initial set of records and make copies for each unit test.

So, let's add a line between the two blocks and change the filename in the second constructor call.

File.Copy("testdata.db", "copydata.db");
using (var db = new TestDataContext("copydata.db"))

It appears that despite calling SaveChanges and closing the using block, the file on disk doesn't have the updates. When the code attempts to read the first record and display the first Name value, it throws an exception complaining that the table is missing.

How can I commit all the changes made through Entity Framework Core such that I can copy the file with all the changes included.

(Note: I've not included the code for TestDataContext as it is a completely ordinary Entity Framework Core custom context with a call to UseSqlite in the OnConfiguring call, passing in "Data Source=" followed by the filename supplied to the constructor call. If you really need it to answer the question, please leave a comment.)

CodePudding user response:

Add Pooling=false to your connection string and use a full path to the file to avoid confusion

  • Related