逛逛上下文不是构造的。添加默认的构造函数或提供IDbContextFactory的实现&QUOT。 [英] Getting 'Context is not constructible. Add a default constructor or provide an implementation of IDbContextFactory."

查看:2339
本文介绍了逛逛上下文不是构造的。添加默认的构造函数或提供IDbContextFactory的实现&QUOT。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用code首先迁移我收到此错误。

I am getting this error when I try to use code first migrations.

我的背景有连接名称的构造。

My context has a constructor with the connection name.

public class VeraContext : DbContext, IDbContext
{
    public VeraContext(string NameOrConnectionStringName = "VeraDB")
        : base(NameOrConnectionStringName)
    {
    }

    public IDbSet<User> Users { get; set; }
    public IDbSet<Product> Products { get; set; }
    public IDbSet<IntCat> IntCats { get; set; }
}

此连接名称与ninject注射时的项目运行,我还指定了它作为默认如上面的code,但这并没有帮助。

This connection name is injected with ninject when the project runs, I have also specified it as a default as in the above code but this did not help.

kernel.Bind<IDbContext>()
    .To<VeraContext>()
    .WithConstructorArgument("NameOrConnectionStringName", "VeraDB");

当我尝试使用启用的迁移被抛出了错误添加迁移:

When I try to add migrations with "Enable-Migrations" is throws up the error:

目标上下文VeraData.EF.Infrastructure.VeraContext'不是
  构造的。添加一个默认的构造函数或提供实现
  的IDbContextFactory。

The target context 'VeraData.EF.Infrastructure.VeraContext' is not constructible. Add a default constructor or provide an implementation of IDbContextFactory.

如果我删除 VeraContext 构造,将工作但 VeraData.EF.Infrastructure.VeraContext 作为其名称。

If I remove the constructor from VeraContext it will work but creates another database with VeraData.EF.Infrastructure.VeraContext as its name.

我presume的 ninject 仅通过连接字符串时,该项目的运行,而不是当我用code首先迁移。无论如何,我可以注入/提供连接的名称默认使用code首先迁移时?

I presume that ninject only passes the connection string when the project runs and not when I use code first migrations. Anyway I can inject/provide a default for the connection name when using code first migrations ?

推荐答案

从本质上讲,你需要一个默认的构造函数(这是错误) - 只是实现它会导致问题。

Essentially you need a default ctor (that's the error) - but just implementing it would lead to problems.

您不得不实施 IDbContextFactory 的结果是一致的(或code迁移将无法正常工作等)。

You'd have to implement the IDbContextFactory for the results to be consistent (or your migration from code won't work etc.).

迁移实际上是调用你的默认构造函数使一个
  连接。所以你其他男星将没有多大意义。

Migrations actually call your default constructor to make a connection. So you're other ctor won't matter much.

下面是基本的工厂...

Here is the basic factory...

public class MyContextFactory : IDbContextFactory<MyContext>
{
    public MyContext Create()
    {
        return new MyDBContext("YourConnectionName");
    }
}

您应该再加上注射,注入和构建你的DbContext如你所愿。

You should combine that with injection, to inject and construct your DbContext as you wish.

这篇关于逛逛上下文不是构造的。添加默认的构造函数或提供IDbContextFactory的实现&QUOT。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆