0

In my current app, all data is stored in an database using entity framework.

I now like to implement an "export/backup to file" functionality and the corresponding "import/restore from file" functionality within the app, agnostic of the underlying database, not using the backup/restore methods of the database.

A restore should take the data to the state it was in right before the backup, so changes after that should be discarded.

It breaks down to the following parts for backup:

  • load all entities (from root entities to childs) from database
  • serialize objects to string
  • write this string to file

And for restore:

  • read file
  • deserialize file content to objects
  • remove all existing entities in database
  • write all entities to database

The backup part is mostly done by using the code of this post (https://stackoverflow.com/a/49597502/226278) and using JSON.net for serializing the resulting data:

var data = db.Set<Blog>().Include(db.GetIncludePaths(typeof(Blog))).ToList(); // both Include() and GetIncludePaths() from https://stackoverflow.com/a/49597502/226278
var stringToFile = JsonConvert.SerializeObject(data, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
// write string to file

Also most parts of restore are done:

// read string from file
var data = JsonConvert.DeserializeObject<List<Blog>>(stringFromFile, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
_context.AddRange(data);
_context.SaveChanges();

What I'm struggling with is the cleanup of the database before restoring all entities. What would be the best, most EF core way of doing this?

Also this should be independent of the underlying database, so any solutions including ExecuteSqlCommand() are probably not what I want.

sc911
  • 1,130
  • 10
  • 18

1 Answers1

0

can you rename the old database and start with a fresh schema to insert the data into?

terrencep
  • 675
  • 5
  • 16
  • no, it should be controllable from within the app and completely independent of the database – sc911 Jan 29 '20 at 16:44