0

使用实体框架命令(“7.0.0-beta1”)时。

跑步时

k ef 迁移添加 InitialCreate

我收到错误。

[解决方案]

我尝试将我的类文件(创建 DbContext 的位置)从单独的类库移动到主项目,并且一切都按预期工作。

所以真正的问题是在单独的类库中使用 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);
    }

}
4

1 回答 1

0

如果您在类库中创建 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 OnConfiguring 方法来设置连接字符串

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");
}
于 2015-01-06T13:17:27.670 回答