How to allow migration for a console application?

后端 未结 1 1322
伪装坚强ぢ
伪装坚强ぢ 2021-02-09 02:09

When using asp.net core and ef core, I have no problem when invoking add-migration init. But when I apply the same approach on a console application below, I got an

相关标签:
1条回答
  • 2021-02-09 03:03

    Important: Don't name your assembly ef (or eF or Ef or EF) to avoid this exception.

    After struggling several hours, I found the solution as follows:

    using EFCore.Models;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Design;
    using Microsoft.Extensions.Configuration;
    using System.IO;
    
    namespace EFCore
    {
        class Program : IDesignTimeDbContextFactory<StudentContext>
        {
            public StudentContext CreateDbContext(string[] args)
            {
                var configurationBuilder = new ConfigurationBuilder()
                  .SetBasePath(Directory.GetCurrentDirectory())
                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
    
                IConfigurationRoot configuration = configurationBuilder.Build();
                string connectionString = configuration.GetConnectionString("Storage");
    
                DbContextOptionsBuilder<StudentContext> optionsBuilder = new DbContextOptionsBuilder<StudentContext>()
                    .UseSqlite(connectionString);
    
                return new StudentContext(optionsBuilder.Options);
            }
    
            static void Main(string[] args)
            {
                Program p = new Program();
    
                using (StudentContext sc = p.CreateDbContext(null))
                {
                    sc.Database.Migrate();
    
                    sc.Students.AddRange
                    (
                        new Student { Name = "Isaac Newton" },
                        new Student { Name = "C.F. Gauss" },
                        new Student { Name = "Albert Einstein" }
                    );
    
                    sc.SaveChanges();
                }
            }
        }
    }
    

    I hope it is also useful for others!

    0 讨论(0)
提交回复
热议问题