【发布时间】:2018-01-21 03:46:47
【问题描述】:
我希望能够在我的 webapi 项目中使用数据库优先方法创建一个带有 entityframework 核心的数据库上下文。 当我这样创作时,效果很好
public class TestingContext : DbContext
{
public TestingContext(DbContextOptions<TestingContext> options)
: base(options)
{
}
public TestingContext()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Data Source=xxxxxx;Initial Catalog=xxxxxx;Integrated Security=False;User Id=xxxxx;Password=xxxxx;MultipleActiveResultSets=True");
}
public DbSet<Information> Information { get; set; }
public DbSet<ArticleUser> ArticleUser { get; set; }
}
我必须添加行 services.AddDbContext 以使其工作。
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddCors();
//using Dependency Injection
services.AddSingleton<Ixxx, xxx>();
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddDbContext<TestingContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
// Register the Swagger generator, defining one or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "Articles API", Version = "v1" });
});
}
如果我从我的 TestingContext 中删除此方法
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Data Source=xxxxxx;Initial Catalog=xxxxxx;Integrated Security=False;User Id=xxxxx;Password=xxxxx;MultipleActiveResultSets=True");
}
我收到以下错误。
没有为此 DbContext 配置数据库提供程序。 可以通过覆盖 DbContext.OnConfiguring 方法或 通过在应用程序服务提供者上使用 AddDbContext。如果使用 AddDbContext, 然后还要确保您的 DbContext 类型在其 构造函数并将其传递给 DbContext 的基本构造函数。
为什么我需要在两个地方将我的连接字符串传递给数据库,然后才能提取我的数据。请协助。我是新来的核心。这两个地方是配置服务方法和上下文本身。
【问题讨论】:
-
您的 DbContext 是否位于不同的程序集中?你有project.json(VS2015)项目还是csproject(VS2017)?
-
不,它不在不同的程序集中。我在同一个项目中创建了一个类。是的,我确实有 project.json(与 2015 相比)
-
当
DbContext位于类库中而不是在 ASP.NET Core 项目中并且从该类库调用dotnet ef database scaffold ...时,通常会出现此错误,请参阅.NET Standard Limitations跨度> -
删除你的无参数构造函数。您可以选择删除您的
OnConfiguring方法。
标签: asp.net-core entity-framework-core dbcontext