Question

One of my EF migrations creates a table and as part of the migration Up method I would like to fill this table with initial data.

Here's my migration class:

public partial class Objects : DbMigration
{
    void Fill(string table, string path, string fieldTerminator = ",", string rowTerminator = @"\n")
    {
        Sql(string.Format("BULK INSERT {0} FROM '{1}' WITH (FIELDTERMINATOR = '{2}', ROWTERMINATOR = '{3}')", table, path, fieldTerminator, rowTerminator));
    }

    public override void Up()
    {
        CreateTable(
            "dbo.Objects",
            c => new
                {
                    ObjectId = c.Int(nullable: false),
                    Name = c.String(),
                    Location_X = c.Double(nullable: false),
                    Location_Y = c.Double(nullable: false),
                    Location_Z = c.Double(nullable: false),
                })
            .PrimaryKey(t => t.ObjectId);

        Fill("dbo.Objects", @"C:\temp\Scratch\Junk\ConsoleApplication3\data\objects.csv");
    }

    public override void Down()
    {
        DropTable("dbo.Objects");
    }
}

This works correctly on my machine from the Package Manager Console. However I would like to use a relative path for the file so that the entire development team can use this easily.

When I simply wrote the file name the update failed. When I tried concatenating the current directory to the file name I saw that the current directory was c:\windows\system32.

How can I make the update run from the project or solution directory?

Alternatively, is there a better way to fill the table during an update? I don't want to use the Seed method becasue it doesn't do exactly what I want. For instance, there's only a single Seed method while I want to write different code for different migrations.

Was it helpful?

Solution

As a workaround you may get path to the current source file and then to enter to relative path of the CSV file with data.

Meaning instead of:

dataFile = @"C:\temp\Scratch\Junk\ConsoleApplication3\data\objects.csv";

Have something like:

currentFile = GetSourceFilePath(); // See below hints for implementation
dataFile = Path.Combine(
    Path.GetDirectoryName(currentFile),
    @"..\data\objects.csv"
);

Here are some examples of how exactly to get access to source file path - Print the source filename and linenumber in C#.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top