【发布时间】:2020-10-04 04:20:15
【问题描述】:
在使用asp.net core和ef core时,调用add-migration init没有问题。但是当我在下面的控制台应用程序上应用相同的方法时,我收到一条错误消息:
无法创建“StudentContext”类型的对象。将“IDesignTimeDbContextFactory”的实现添加到项目中,或查看https://go.microsoft.com/fwlink/?linkid=851728 了解设计时支持的其他模式。
解决此问题的最简单方法是什么?
.net核心控制台应用项目如下:
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
要求:我不想通过默认的无参数构造函数或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();
}
}
}
}
【问题讨论】:
标签: c# console-application entity-framework-core