Reputation: 110
I trying to backup data on Model change and recreate it after database creation. It's work fine but I need to write this for each class. How can I get all DbSet in DbContext and loop with this functions on it?
backup:
XmlSerializer classSerializer = new XmlSerializer(typeof(List<TextComponent>));
StreamWriter classComponentWriter = new StreamWriter(Server.MapPath("~/App_Data/backup/TextComponents.xml"));
classSerializer.Serialize(classComponentWriter, _db.TextComponents.ToList());
classComponentWriter.Close();
restore:
List<TextComponent> TextComponents = null;
XmlSerializer TextComponentSerializer = new XmlSerializer(typeof(List<TextComponent>));
FileStream TextComponentFileStream = new FileStream(Server.MapPath("~/App_Data/backup//TextComponents.xml"), FileMode.Open);
TextComponents = (List<TextComponent>)TextComponentSerializer.Deserialize(TextComponentFileStream);
foreach (TextComponent item in TextComponents)
{
_db.TextComponents.Add(item);
}
_db.SaveChanges();
Upvotes: 0
Views: 1224
Reputation: 14787
You can use reflection to enumerate all DBSet properties:
properties = typeof(DBContext).GetProperties(); // or this.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
if (/*Check if property type is DBSet by comparing [property.DeclaringType](http://msdn.microsoft.com/en-us/library/system.type.declaringtype.aspx)*/)
// Write backup or restore code here.
}
`
Upvotes: 1