How to create Function in Database with Migrations Ef core?

Asked

Viewed 151 times

1

I created a Function in Postgresql and would like it to be generated together with the database in the initial Migration.

I tried it this way and I didn’t get any results

 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
            Database.GetDbConnection().CreateCommand().CommandText = "função vai aqui";
 }

2 answers

2


Use the add-Migration and personalize the migration.

Sometimes it is useful to add a migration without making changes to template. In this case, adding a new migration creates code with empty classes. You can customize this migration to perform operations that are not directly related to the RU model Core.

Example of migration customized:

public partial class MinhaFuncao : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        var function = @"
                    CREATE FUNCTION MINHAFUNCAO(@ST VARCHAR(1000))
                    RETURNS VARCHAR(1000)
                    BEGIN
                       RETURN('Minha função')
                    END
                ";

        migrationBuilder.Sql(function);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {

    }
}
  • Hello George, I did so: public class Applicationdbcontext : Dbcontext { protected override void Onmodelcreating(Modelbuilder modelBuilder) { Database.Executaesqlcommand("sql script of the function here"); } } ?

  • @iagosoares is valid yes, can even as a response, would be another option :)

  • Thank you George! Sorry for the reply formatting, I’m still learning rsrs

1

Another option found

public class ApplicationDbContext : DbContext
   {
       protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            Database.ExecuteSqlCommand("sql script vai aqui");
        }
   }


Browser other questions tagged

You are not signed in. Login or sign up in order to post.