如何允许控制台应用程序迁移? [英] How to allow migration for a console application?

查看:64
本文介绍了如何允许控制台应用程序迁移?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用asp.net核心和ef核心时,调用 add-migration init 时没有问题。但是,当我在下面的控制台应用程序上应用相同的方法时,出现错误消息:

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:


无法创建 StudentContext类型的对象。将 IDesignTimeDbContextFactory的实现添加到项目中,或参阅 https://go.microsoft。 com / fwlink /?linkid = 851728 了解设计时支持的其他模式。

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?

.net核心控制台应用程序项目如下:

The .net core console application project is as follows:

{
  "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


要求:我不想通过默认的无参数构造函数或 OnConfiguring <>在 StudentContext 类中对连接字符串进行硬编码。 / code>方法。

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();
            }
        }
    }
}


推荐答案

重要:不要将程序集命名为 ef (或 eF Ef EF )以避免此异常

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!

这篇关于如何允许控制台应用程序迁移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆