使用实体框架命令时("7.0.0-beta1")。
运行时
k ef migration add InitialCreate
我收到错误。
[解决方案]
我尝试将我的类文件(创建 DbContext 的位置)从单独的类库移动到主项目,并且所有内容都按预期工作。
所以真正的问题是在单独的类库中使用 DbContext 时。
我的数据库上下文文件
public class DbTables : DbContext
{
public DbSet<class_name> class_name_alias { get; set; }
private static bool _created = false;
public DbTables()
{
if (_created)
{
Database.AsRelational().ApplyMigrations();
_created = true;
}
}
protected override void OnConfiguring(DbContextOptions options)
{
options.UseSqlServer(@"Data Source=(LocalDB)MSSQLLocalDB;Initial Catalog=app_db;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False");
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
如果在类库中创建 DBContext,若要创建迁移,则必须在此类库的 project.json 中声明 ef 命令。 并为此项目运行 k ef 社区。
{
"version": "1.0.0-*",
"dependencies": {
"EntityFramework.SqlServer": "7.0.0-beta1",
"EntityFramework.Commands": "7.0.0-beta1"
},
"commands": {
"ef": "EntityFramework.Commands"
},
"frameworks" : {
"aspnet50" : {
"dependencies": {
}
},
"aspnetcore50" : {
"dependencies": {
"System.Runtime": "4.0.20-beta-22231"
}
}
}
}
必须重写 On OnConfigure 方法才能设置连接字符串
protected override void OnConfiguring(DbContextOptions options)
{
options.UseSqlServer(@"Data Source=(LocalDB)MSSQLLocalDB;Initial Catalog=app_db;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False");
}