I'm having a bit of a mess around at the moment trying to build a console app where I can insert some data into my database and output the sql to a file as an extra. The idea being is that I could use these for data migrations or something similar.
I have several lookup tables that I'd like to pre-populate with data and I think this is nicer than writing out the sql by hand. If someone needs to look up a value it'll be right there in the code.
I'm using EF Tracing and what I've got so far allows me to log the sql entity framework creates by doing the following
I've hooked into their action to get access to the tracing
private void WriteSqlToString(CommandExecutionEventArgs args)
{
sqlTrace.Append(args.ToTraceString());
}
Which gives something like this
insert [dbo].[Members]([EmailAddress], [FirstName], [LastName])
values (@0, @1, @2)
select [Id]
from [dbo].[Members]
where @@ROWCOUNT > 0 and [Id] = scope_identity()
-- @0 (dbtype=String, size=60, direction=Input) = "email@email.com"
-- @1 (dbtype=String, size=-1, direction=Input) = "TestFirstName"
-- @2 (dbtype=String, size=-1, direction=Input) = "TestLastName"
I'll be the first to hold my hand up because I'm not good at writing sql by hand. I've messed about with this a little to try and get it to execute in sqlserver express but keep getting errors because the variables aren't declared.
Do folk think it's worth continuing trying to get this to work or am I missing a better solution here?
Here's some more of the code for reference
public void CreateSqlFile()
{
using (MyContext context = tracingContextFactory.Create(WriteSqlToString))
{
Migrate(context);
context.SaveChanges();
}
StreamWriter file = new StreamWriter(migrationPath);
file.WriteLine(sqlTrace.ToString());
file.Close();
}