Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow migration for a console application?

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 error saying:

Unable to create an object of type 'StudentContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

What is the easiest way to fix this issue?

The .net core console application project is as follows:

appsettings.json

{
  "ConnectionStrings": {
    "Storage": "Data Source=storage.db"
  }
}

EFCore.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.1" />
    <PackageReference Include="Microsoft.Extensions.Configuration" Version="2.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.0.0" />
  </ItemGroup>

</Project>

Student.cs

namespace EFCore.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

StudentContext.cs

Requirement: I don't want to hard code the connection string in StudentContext class via either default parameterless constructor or OnConfiguring method.

using Microsoft.EntityFrameworkCore;

namespace EFCore.Models
{
    public class StudentContext : DbContext
    {
        public StudentContext(DbContextOptions<StudentContext> options) : base(options) { }

        public DbSet<Student> Students { get; set; }
    }
}

Program.cs

using EFCore.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.IO;

namespace EFCore
{
    class Program
    {
        static void Main(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);

            using (StudentContext sc = new StudentContext(optionsBuilder.Options))
            {

                sc.Database.Migrate();

                sc.Students.AddRange
                (
                    new Student { Name = "Isaac Newton" },
                    new Student { Name = "C.F. Gauss" },
                    new Student { Name = "Albert Einstein" }
                );

                sc.SaveChanges();
            }
        }
    }
}
like image 577
In Vladimir Putin We Trust Avatar asked Jan 21 '18 02:01

In Vladimir Putin We Trust


1 Answers

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!

like image 107
In Vladimir Putin We Trust Avatar answered Oct 16 '22 14:10

In Vladimir Putin We Trust