当我尝试使用代码优先迁移时收到此错误。
我的上下文有一个带有连接名称的构造函数。
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/