Search code examples
asp.net-web-apinhibernatemigrationcode-firstevolve

How to do migration using evolve in asp .net core with nhibernate?


I have to create a table in PSql database using code first approach in asp .net core with nHibernate ORM. I have tried evolve migration. I didn't get any error but table is not created in the database. I don't know what's wrong in that. Here is my code that I have used in Program.cs. Please let me know how to do migration.

 public static IHostBuilder CreateHostBuilder(string[] args)
    {

        var target = Host.CreateDefaultBuilder(args)
             .ConfigureWebHostDefaults(webBuilder =>
             {
                 string env = webBuilder.GetSetting("ENVIRONMENT");
                 env = string.IsNullOrEmpty(env) ? "Production" : env;

                 var builder = new ConfigurationBuilder()
                 .SetBasePath(Directory.GetCurrentDirectory())
                 .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                 .AddJsonFile($"appsettings.{env}.json", optional: true)
                 .AddEnvironmentVariables();

                 var configuration = builder.Build();

                 var connectionString = configuration.GetValue<string>(ConfigKeyNames.ConnectionString);
                 var connection = new Npgsql.NpgsqlConnection(connectionString);
                 var evolve = new Evolve.Evolve(connection, msg => Log.Information(msg))
                 {
                     EmbeddedResourceAssemblies = new[] { typeof(SampleUserModel).Assembly },
                     IsEraseDisabled = (env == "Production"),
                     MustEraseOnValidationError = (env == "Production")
                 };

                 evolve.Migrate();

                 webBuilder.UseStartup<Startup>();
           });

        return target;
    }

Thanks in advance..


Solution

  • I did a mistake in create script column names so that the table is not created in database.

    "id" bigint NOT NULL
    

    Column names in PSQL create script do not enclosed in double quotes. Here is my correct PSQL create table script for migration.

     CREATE TABLE public.sampleuser
     (
     id bigint NOT NULL ,
     userid bigint,
     name character varying(50) COLLATE pg_catalog."default",
     address character varying(100) COLLATE pg_catalog."default",
     phonenumber bigint,
     isactive boolean,
     CONSTRAINT SampleUser_pkey PRIMARY KEY (id)
     );
    
    CREATE SEQUENCE public.sampleuser_seq
     INCREMENT 1
     START 1
     MINVALUE 1
     MAXVALUE 9223372036854775807
     CACHE 100;