0

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();

1 Answer 1

1

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.  
}  

`

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.