当我尝试使用代码优先迁移时,我收到此错误.
我的上下文有一个连接名称的构造函数.
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,我也将其指定为上述代码中的默认值,但这没有帮助.
kernel.Bind<IDbContext>() .To<VeraContext>() .WithConstructorArgument("NameOrConnectionStringName","VeraDB");
当我尝试使用“启用迁移”添加迁移时会抛出错误:
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作为名称创建另一个数据库.
我假设ninject只在项目运行时传递连接字符串,而不是当我使用代码第一次迁移时.无论如何,我可以在使用代码首次迁移时注入/提供连接名称的默认值?
解决方法
基本上你需要一个默认的ctor(这是错误) – 但只是实现它会导致问题.
您必须实施IDbContextFactory才能使结果保持一致(或者您的代码迁移将无法正常工作).
Migrations actually call your default constructor to make a
connection. So you’re otherctor
won’t matter much.
这是基本的工厂…
public class MyContextFactory : IDbContextFactory<MyContext> { public MyContext Create() { return new MyDBContext("YourConnectionName"); } }
你应该结合注射,注入和构造你的DbContext,如你所愿.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。