我尝试在模型更改上备份数据,并在创建数据库后重新创建它。 它工作正常,但我需要为每个班级写这个。 如何在DbContext中获取所有DbSet并使用此函数循环?
备份
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();
恢复
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();
答案 0 :(得分:1)
您可以使用反射来枚举所有DBSet属性:
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.
}
`