简体   繁体   中英

backup/restore to/from file with entity framework core independent of database

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.

你能重命名旧数据库并从一个新的模式开始插入数据吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM