在Asp.netCore中没有为此DbContext配置get方法的数据库提供程序

时间:2017-01-01 11:55:07

标签: c# asp.net-web-api asp.net-core entity-framework-core

我通过Asp.net核心创建一个web api项目,我添加了一个api控制器(名称为BlogController),在博客控制器中我有一个get方法GetAllBlog这是我的控制器:

[Route("api/[controller]")]
public class BlogController : Controller
{
    private static Logger logger = LogManager.GetCurrentClassLogger();

    public IContext _context { get; set; }
    public BlogController(IContext ctx)
    {
        _context = ctx;
    }

    [HttpGet]
    public IEnumerable<Blog> GetAllBlog()
    {
        return _context.Blogs.ToList();
    }
 }

这是我的IContext和模型:

public interface IContext : IDisposable
{
    DbSet<Blog> Blogs { get; set; }
    DbSet<Post> Posts { get; set; }
    int SaveChanges();
}

和上下文:

public class Context : DbContext, IContext
{
    public Context(DbContextOptions<Context> options) : base(options)
    { }
    public virtual DbSet<Blog> Blogs { get; set; }
    public virtual DbSet<Post> Posts { get; set; }
}

和型号:

public class Blog
{
    public int BlogId { get; set; }
    public string Name { get; set; }
    public string Url { get; set; }
    public DateTime? CreationDate { get; set; }
    public virtual IList<Post> Posts { get; set; }
}

当我致电GetAllBlog()时,我收到了这个错误:

  

没有为此DbContext配置数据库提供程序。可以通过覆盖DbContext.OnConfiguring方法或在应用程序服务提供程序上使用AddDbContext来配置提供程序。如果使用AddDbContext,那么还要确保您的DbContext类型在其构造函数中接受DbContextOptions对象,并将其传递给DbContext的基础构造函数。   有什么问题?

更新:这是configurationservice类中的Startup方法:

public void ConfigureServices(IServiceCollection services)
{
    var connection = @"Data Source=.;Initial Catalog=RestfullServices;Integrated Security=true";
    services.AddDbContext<Context>(options => options.UseSqlServer(connection));
    services.AddScoped<IContext>(p => new Context(new DbContextOptions<Context>()));
    services.AddApplicationInsightsTelemetry(Configuration);
    services.AddMvc();
}

1 个答案:

答案 0 :(得分:2)

配置DbContext时

services.AddDbContext<Context>(options => options.UseSqlServer(connection));

您将其配置为使用特定选项options.UseSqlServer(connection)

但在配置范围上下文抽象时

services.AddScoped<IContext>(p => new Context(new DbContextOptions<Context>()));

正在创建一个新的Context,其配置与之前配置的完全不同。

通过更改IContext在启动期间向DI框架注册的方式,如此

services.AddScoped<IContext, Context>();

在创建AddDbContext的实例时,DI框架将使用Context配置,在创建DbContext的实例时,它将具有您希望在启动配置中使用的选项。

Startup.ConfigurServices最终看起来像这样......

public void ConfigureServices(IServiceCollection services) {
    var connection = @"Data Source=.;Initial Catalog=RestfullServices;Integrated Security=true";
    services.AddDbContext<Context>(options => options.UseSqlServer(connection));
    services.AddScoped<IContext, Context>();
    services.AddApplicationInsightsTelemetry(Configuration);
    services.AddMvc();
}