1

I'm using ASP.NET Core and Entity Framework Core. I need to create some views and functions programmatically on the app first start. Is there a way to run some custom SQL code while EF is being configurated?

3 Answers 3

3

If you are using code first with entity, you can try execute your sql scripts in migration:

First you need to create a migration:

Add-Migration RunMySqlScripts

Then in the generated migration file you can write your SQL:

// PLAIN SQL
Sql("Your sql code here");

// OR FROM FILE
var sqlFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"scripts.sql"); 
Sql(File.ReadAllText(sqlFile));

Then you run:

Update-Database

This will be executed only once.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! It work with some little changes: var sqlFile = Path.Combine(AppContext.BaseDirectory,"up.sql"); migrationBuilder.Sql(File.ReadAllText(sqlFile));
0

I use this class for myself. That will run the code only once after the database was initialized.

public class MyDataInitializer
{
    public async Task InitializeDatabaseAsync(IServiceProvider serviceProvider)
    {
        var db = serviceProvider.GetService<MyCustomDB>();
        var databaseCreated = await db.Database.EnsureCreatedAsync();
        if (databaseCreated)
        {
            await GenerateData(db);
        }
    }

    private static async Task GenerateData(MyCustomDB context)
    {
        context.Users.Add(new User
        {
            Name = "admin",
            PasswordParam = "pwd",
        });

        await context.SaveChangesAsync();

        // or execute custom sql here
    }
}

And at the end of Startup.Configure(IApplicationBuilder app, ...)

MyDataInitializer dataInitializer = new MyDataInitializer();
await dataInitializer.InitializeDatabaseAsync(app.ApplicationServices);

Comments

-1

Loads of approaches you could use here, personally I would either use StartUp with a Configure method or a static constructor on the EF context.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.