Can I generate migration seeds from an sql script?

Viewed 60

I'm using Sqlserver and .NETCore to create backend for my project.

and I have so many tables with so much data. I was wondering, is there a way to generate seeds to use in my migration from the existing db tables? i.e : I want to generate this from the table FamilyMemberPrivileges

modelBuilder.Entity<FamilyMemberPrivileges>().HasData(
                new FamilyMemberPrivileges
                {
                    Id = 1,
                    Name = "full control"
                },
                new FamilyMemberPrivileges
                {
                    Id = 2,
                    Name = "control over self"
                },
                new FamilyMemberPrivileges
                {
                    Id = 3,
                    Name = "read-only"
                }
            );

I have searched everywhere for this, maybe it doesnt work like that. but no harm in asking! also, if this is not possible, is there an easier way to do this instead of writing the seeds myself?

Thanks!

1 Answers

You can write a Sql Statement that returns C# code and run it in SSMS. An example will be like:

select 'new FamilyMemberPrivileges{ Id ='+ convert(varchar(10), [Id] )+ ', Name="'+ [Name] + '"},'
from dbo.FamilyMemberPrivileges

The result will look like this

-------------------------------------------------------------------------------
new FamilyMemberPrivileges{ Id =1, Name="Full Control"},
new FamilyMemberPrivileges{ Id =2, Name="Control Over Self"},

(2 rows affected)

And then copy + paste the result to your code

Related