Mar*_*ert 6 c# entity-framework-core
我正在尝试使用EF Core工具来管理我在C#类库中设计的SqlServer数据库.它位于类库中,因为我需要在MVC6网站和一些命令行工具中使用数据库模式.
我不得不将类库转换为netapp,因为当前版本的工具不支持类库,但我不认为这是我的问题的根源.
我的DbContext类看起来像这样:
public class ConnellDbContext : IdentityDbContext<ConnellUser>
{
public ConnellDbContext( DbContextOptions<ConnellDbContext> options )
{
}
// core tables
public DbSet<Ballot> Ballots { get; set; }
public DbSet<Campaign> Campaigns { get; set; }
//...
}
Run Code Online (Sandbox Code Playgroud)
当我在程序包管理器控制台上运行"dotnet ef迁移列表"时,收到以下错误消息:
在'ConnellDbContext'上找不到无参数构造函数.要么将无参数构造函数添加到'ConnellDbContext',要么在与'ConnellDbContext'相同的程序集中添加'IDbContextFactory'的实现.
我不太清楚如何解决这个问题.插入无参数构造函数很容易,但是当我这样做时,我得到以下错误:
没有为此DbContext配置数据库提供程序.可以通过覆盖DbContext.OnConfiguring方法或在应用程序服务提供程序上使用AddDbContext来配置提供程序.如果使用AddDbContext,那么还要确保您的DbContext类型在其构造函数中接受DbContextOptions对象,并将其传递给DbContext的基础构造函数.
我>>想想<<这意味着控制台命令没有在我的appsettings.json文件中获取连接字符串信息:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-ConnellCampaigns;Trusted_Connection=True;MultipleActiveResultSets=true;AttachDbFilename=e:\\SqlServer\\Data\\ConnellCampaigns.mdf;"
}
}
Run Code Online (Sandbox Code Playgroud)
我遗漏了一些关于EF工具如何访问源代码以实现其魔力的东西.任何指针或线索都将非常感激.
附加信息
对安德森先生来说,我已经取得了一些进展.我添加了一个无参数构造函数并覆盖了我的DbContext类中的OnConfiguring()方法:
protected override void OnConfiguring( DbContextOptionsBuilder optionsBuilder )
{
var builder = new ConfigurationBuilder()
.AddJsonFile( "appsettings.json", optional: true, reloadOnChange: true );
IConfigurationRoot config = builder.Build();
optionsBuilder.UseSqlServer(config.GetConnectionString("DefaultConnection") );
}
Run Code Online (Sandbox Code Playgroud)
这不起作用,但在UseSqlServer()的调用中明确包含实际的连接字符串.关于为什么基于"DefaultConnection"的呼叫不起作用的想法?
public class ConnellDbContext : IdentityDbContext<ConnellUser>
{
internal static string connection_string
{
get
{
return System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}
}
public ConnellDbContext() : base(connection_string)
{
}
// core tables
public DbSet<Ballot> Ballots { get; set; }
public DbSet<Campaign> Campaigns { get; set; }
//...
}
Run Code Online (Sandbox Code Playgroud)