2012-02-19 124 views
0

我想備份數據對模型的變化和創建數據庫後重新創建它。 它工作正常,但我需要爲每個班級寫這個。 如何獲取DbContext中的所有DbSet並使用此功能循環?實體框架代碼優先 - 備份和恢復的DbContext

備份:

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

回答

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

`