【问题标题】:Configuring DbContext Constructor配置 DbContext 构造函数
【发布时间】:2016-12-13 00:18:08
【问题描述】:

我正在尝试使用 EF Core 工具来管理我在 C# 类库中设计的 SqlServer 数据库。它在类库中,因为我需要在 MVC6 网站和一些命令行工具中使用数据库模式。

我不得不将类库转换为 netapp,因为当前版本的工具不支持类库,但我认为这不是我的问题的根源。

我的 DbContext 类如下所示:

public class ConnellDbContext : IdentityDbContext<ConnellUser>
{
    public ConnellDbContext( DbContextOptions<ConnellDbContext> options )
    {
    }

    // core tables
    public DbSet<Ballot> Ballots { get; set; }
    public DbSet<Campaign> Campaigns { get; set; }
    //...
}

当我在包管理器控制台上运行“dotnet ef 迁移列表”时,我收到以下错误消息:

在“ConnellDbContext”上找不到无参数构造函数。任何一个 将无参数构造函数添加到“ConnellDbContext”或添加 'IDbContextFactory' 的实现 汇编为“ConnellDbContext”。

我不太确定如何解决这个问题。插入无参数构造函数很容易,但是当我这样做时,会出现以下错误:

没有为此 DbContext 配置数据库提供程序。一种 可以通过覆盖 DbContext.OnConfiguring 来配置提供程序 方法或通过在应用程序服务提供者上使用 AddDbContext。 如果使用了 AddDbContext,那么还要确保你的 DbContext 类型 在其构造函数中接受一个 DbContextOptions 对象,并且 将其传递给 DbContext 的基本构造函数。

我 >>认为

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-ConnellCampaigns;Trusted_Connection=True;MultipleActiveResultSets=true;AttachDbFilename=e:\\SqlServer\\Data\\ConnellCampaigns.mdf;"
  }
}

我错过了一些关于 EF 工具如何访问源代码以发挥其魔力的信息。任何指针或线索将不胜感激。

其他信息

感谢安德森先生,我取得了一些进展。我在 DbContext 类中添加了一个无参数构造函数并覆盖了 OnConfiguring() 方法:

protected override void OnConfiguring( DbContextOptionsBuilder optionsBuilder )
{
    var builder = new ConfigurationBuilder()
        .AddJsonFile( "appsettings.json", optional: true, reloadOnChange: true );

    IConfigurationRoot config = builder.Build();

    optionsBuilder.UseSqlServer(config.GetConnectionString("DefaultConnection") );
}

这不起作用,但在对 UseSqlServer() 的调用中明确包含实际的连接字符串确实有效。关于为什么基于“DefaultConnection”的调用不起作用的想法?

【问题讨论】:

  • 没有这样的魔法。 EF 采用单例模型,每个 T 都有一个 DbContext 的静态实例。然而,为了创建实例,它需要无参数 ctor。
  • 但是为什么当我添加这样一个 ctor 时它会卡住呢?
  • 看起来 EF 不知道要将您的上下文绑定到哪个数据库连接。您是否尝试在 ConnellDbContext 中覆盖 OnConfiguring()
  • 不,我没试过。在我理解的范围内,我阅读的文档似乎说提供无参数 ctor 或覆盖 OnConfiguring() 都可以。前者似乎更容易。但我认为我没有正确设置无参数 ctor(此时它只是一个空方法)。

标签: c# entity-framework-core


【解决方案1】:
public class ConnellDbContext : IdentityDbContext<ConnellUser>
{
    internal static string connection_string
    {
        get
        {
            return System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        }
    }

    public ConnellDbContext() : base(connection_string)
    {

    }
    // core tables
    public DbSet<Ballot> Ballots { get; set; }
    public DbSet<Campaign> Campaigns { get; set; }
    //...
}

【讨论】:

  • 那么connection_string从何而来?
  • @JohnyL 您可以创建从配置中读取连接字符串的属性。让我编辑我的答案。
  • @JohnyL 现在有意义了吗?
  • 首先,这是 EF Core - 连接字符串必须在 OnConfiguring 方法中使用。其次,忘记第一点,你将如何传递连接字符串?您的 ConnellDbContext 的构造函数没有接收到连接字符串 - 它没有任何东西可以传递给 base
  • @JohnyL 你是对的! .Net Core 是不同的。
猜你喜欢
  • 1970-01-01
  • 2019-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-04
  • 1970-01-01
  • 1970-01-01
  • 2014-02-26
相关资源
最近更新 更多