Search code examples
c#entity-frameworkentity-framework-6.1

Read data during migration


I have the following scenario:

Module A & B have their settings stored in an XML file. Module C has its settings stored in the DB (table with one row). Now I would like to move the settings from Module C to the XML file where A & B store their respective settings.

When I delete the SettingsC entity in the settings table will be deleted on the next migration.

Is there a way to read the tables content during that migration and write it to the XML file before the table is deleted?

EXAMPLE:

public partial class DropModuleCSettings : DbMigration
{
    public override void Up()
    {
        // here I would like to read the content of "dbo.SettingsC"
        DropTable("dbo.SettingsC");
    }

    public override void Down()
    {
        // ...
    }
}

Solution

  • I'm not sure about the timing of "When" to get the data out of the ModuleC Database table but you are probably going to be looking at:

    http://blogs.msdn.com/b/saurabh_singh/archive/2010/05/11/export-sql-table-records-to-xml-form.aspx

    Basically:

    SELECT * FROM SettingsC FOR XML AUTO
    

    This will give you the contents of your table in an XML file.

    To retrieve this information do something along the lines of:

    using (SqlConnection oCn = new SqlConnection())
    {
        oCn.ConnectionString = @"server=sql-server\cos;integrated security=SSPI;database=daas5";
        oCn.Open();
    
        // Create a SQL command object.
        string strSQL = "SELECT * FROM SettingsC FOR XML AUTO";
    
        SqlCommand myCommand = new SqlCommand(strSQL, oCn);
        //Read you query into an XmlReader
        XmlReader reader = myCommand.ExecuteXmlReader();        
    } 
    

    Once you have that, you can easily load this into an XDocument

    XDocument doc = XDocument.Load(reader);
    

    or an XmlDocument

    XmlDocument xdoc = new XmlDocument();
    xdoc.Load(reader);