c# - 如何允许控制台应用程序迁移?

标签 c# console-application entity-framework-core

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

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.

解决此问题的最简单方法是什么?

.net core控制台应用项目如下:

应用设置.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>

学生.cs

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

StudentContext.cs

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

using Microsoft.EntityFrameworkCore;

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

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

程序.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(或 eFEfEF ) 来避免 this exception .

经过几个小时的努力,我找到了解决方案如下:

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

我希望它对其他人也有用!

关于c# - 如何允许控制台应用程序迁移?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48363173/

相关文章:

c# - 在 Windows 中监听端口是否比在 Linux 中慢?

C++ 编程练习——深度复制

C# 计算目录大小

c# - EntityFrameworkCore.PostgreSQL 转换点

c# - 检查解决方案中的二进制引用

c# - 私有(private)访问与公共(public)访问

asp.net - 使用没有 XSLT 的 ASP.NET 控制台应用程序进行 XML 动态转换的哪种合适方式?

c# - 如何在类库项目中首先使用 EF Core Code 创建数据库

c# - EF Core 添加迁移调试

c# - 将 JArray 对象转换为动态 ExpandoObjects 列表的最佳方法