We have custom code that wipes and initializes our test database by creating a few objects and saving them to the DatabaseContext (we use Migrations for the schema, but not for the data). However, our tester has created a lot more data, and doesn’t want to lose her test data when we do a clean deploy. I therefore have to figure out how to get the data from SQL Server into C# (once off), so it an be run with our data-initialization program.
My initial approach was to manually copy-paste the data into C# object initializers, but this got old quickly, since there are 100+ rows to copy.
My second approach was to create the objects using a SELECT statement in SQL Server, mixing the C# initializer syntax into the SQL SELECT statement, and then copying the C# strings generated by SQL Server back into Visual Studio.
Although the second approach seems OK, I was wondering if there’s an obvious solution (apart from simply running a SQL INSERT script every time) that I am missing.
I ended up going with the approach mentioned in the question. Generating C# object initialializers in SQL Select Statements.
A few things I picked up, mostly obvious:
CAST AS VARCHAR for all numeric fields (although SQL Server will give error if you don’t).
Dates: convert to VARCHAR and surround with DateTime.Parse()
Use a CASE statement to convert SQL bool value (1/0) to true/false as strings.
Enums: generate a cast.
If using autonumber ids, remember to prefix instance names with a letter(s). Add the object to DataContext after initializing it.
Don’t be afraid to reference your C# code in the generated code. It isn’t going to run in SQL Server in any case.