我的项目中有一个带有 EF Core 的 SQL Server 数据库,我想在另一个表中添加一个表和一个列。但是当我Add-Migration在 PM 控制台中运行时,我收到此错误
An item with the same key has already been added. Key: MyProject.Model.MyContext
MyProject我的 asp.net core 项目和MyContextDbContext 类在哪里。
我的 DbContext 类看起来像
namespace MyProject.Model
{
public class MyContext : DbContext
{
public MyWorker Worker { get; private set; }
/// <summary>
/// initialize the worker instance to get the crud methods of the database
/// </summary>
public MyContext()
{
Worker = new MyWorker(this);
}
public static string GetConnectionString() …Run Code Online (Sandbox Code Playgroud) c# entity-framework entity-framework-core entity-framework-migrations
我正在使用 Entityframework Core 和代码优先方法设置一个新数据库。我已经在下面的代码清单中设置了一个上下文类,以及数据库表的所有需要的类。现在我想用
using (var context = new MyContext())
{
context.Database.EnsureCreated();
}
Run Code Online (Sandbox Code Playgroud)
但我得到的是一个错误,连接字符串不能为空。
我的 Connectionstring 在 appsettings.json 文件中设置,我在项目构建时将其复制到输出目录。
我尝试了不同的方法来从 appsettings 文件中获取连接字符串,但结果都相同。在 Startup 类的 Configuration 属性中,我可以看到 appsettings 文件已正确加载,但是当我想获取字符串时
ConnectionString = Configuration["Connectionstrings:MyConnection"];
Run Code Online (Sandbox Code Playgroud)
ConnectionString 始终为空。
我的 Startup.cs 文件中有这个:
public class Startup
{
public static string ConnectionString { get; private set; }
public IConfigurationRoot Configuration { get; set; }
public Startup(IHostingEnvironment _environment)
{
Configuration = new ConfigurationBuilder()
.SetBasePath(_environment.ContentRootPath)
.AddJsonFile("appsettings.json")
.Build();
}
Run Code Online (Sandbox Code Playgroud)
在配置 - 方法中有以下内容
using (var context = new MyContext())
{
context.Database.EnsureCreated();
} …Run Code Online (Sandbox Code Playgroud)