我創建了一個由Asp.net核心的web api項目,並且我在博客控制器i中添加了一個api控制器(名稱爲BlogController
)有一個get方法GetAllBlog
這是我的控制器:沒有配置數據庫提供程序用於此DbContext獲取方法在Asp.netCore
[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()
我得到這個錯誤:
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext. what is the problem?
UPDATE:這是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();
}
你也應該顯示在您添加的分貝範圍內 – Nkosi
如何以及在哪裏與你的IoC映射IContext配置?你可以發佈嗎? –
我更新了問題 – pejman