asp.net-mvc-4 - 获取 'Context is not constructible. Add a default constructor or provide an implementation of IDbContextFactory."

标签 asp.net-mvc-4 ef-code-first ninject entity-framework-5 entity-framework-migrations

当我尝试使用代码优先迁移时收到此错误。

我的上下文有一个带有连接名称的构造函数。

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 注入(inject),我也将其指定为默认值,如上面的代码所示,但这没有帮助。

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

当我尝试使用“Enable-Migrations”添加迁移时,会引发错误:

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

如果我从 VeraContext 中删除构造函数,它将起作用,但会创建另一个以 VeraData.EF.Infrastruct.VeraContext 作为名称的数据库。

我认为 ninject 仅在项目运行时传递连接字符串,而不是在我使用代码优先迁移时传递连接字符串。无论如何,我可以在使用代码优先迁移时注入(inject)/提供连接名称的默认值?

最佳答案

本质上你需要一个默认的ctor(这就是错误) - 但仅仅实现它就会导致问题。

您必须实现 IDbContextFactory 才能使结果保持一致(否则您从代码的迁移将不起作用等)。

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

这是基本工厂...

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

您应该将其与注入(inject)结合起来,根据需要注入(inject)并构造您的 DbContext。

关于asp.net-mvc-4 - 获取 'Context is not constructible. Add a default constructor or provide an implementation of IDbContextFactory.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15963726/

相关文章:

asp.net - 如何重现由 asp.net MVC 默认成员身份创建的密码哈希

asp.net-mvc-4 - ASP.NET Web API 授权 token 提前过期

c# - EF 代码优先 - WithMany()

c# - 如何使 ViewModel 验证与模型验证保持同步?

c# - 解析接口(interface)时,Ninject 未解析为已配置的单例

c# - 使用 ninject 的 Asp.net 成员身份提供程序 - 调用 Initialize 方法

c# - ASP.Net 用一个 Controller 创建两个模型

c# - 在强类型 View 中显示来自多个表的数据

entity-framework - Entity Framework 代码优先 : Adding to Many to Many relationship by ID

c# - Ninject - 自动绑定(bind)从通用基类继承的程序集中的所有类(后者又实现通用接口(interface))