DbContext 的 C# 问题:参数 1:无法将 'string' 转换为 'Microsoft.EntityFrameworkCore.DbContextOptions'

C# Problem with DbContext: Argument 1: cannot convert 'string' to 'Microsoft.EntityFrameworkCore.DbContextOptions'

DbContext 我遇到了一些问题。我决定创建一个新的 class,它将负责与数据库的连接。

public class PetAlertContext : DbContext
{
    public PetAlertContext() : base("PetAlert") { }

    public DbSet<Zwierze> Zwierzaki { get; set; }
        public DbSet<Osoba> Osoby { get; set; }
        public DbSet<Placowka> Placowki { get; set; }
        public DbSet<Ogloszenie> Ogloszenia { get; set; }
    }
}

但我在基地名称附近有一些例外:

Argument 1: cannot convert 'string' to 'Microsoft.EntityFrameworkCore.DbContextOptions'.

我发现了类似的问题和类似这样的一些代码的响应,但我在理解这个结构方面有点问题。

你能帮我一下吗?我评论了这些:

public PetAlertContext(string connectionString) : base(GetOptions(connectionString))
{
}

private static DbContextOptions GetOptions(string connectionString)
{
    return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
}

Entity Framework 核心的构造函数不接受单个字符串作为参数,它接受一个DbContextOptions 实例。参见 the documentation here. The constructor you are currently trying to use is the EF6 constructor which does take just the connection string as the parameter (see here). The code you have commented out in your question shows you how to instantiate an instance of DbContextOptions i.e. by using a DbContextOptionBuilder as per the documentation here。因此,假设您使用的是 SQL 服务器数据库,您可以使用该代码。