我使用Asp.net core创建了一个Web API项目,并添加了一个API控制器(名称为BlogController
),在博客控制器中我有一个获取方法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的基础构造函数。问题出在哪里?
Startup
类中的ConfigurationService
方法: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();
}
services.AddScoped<IContext, Context>();
看看是否有效。 - Nkosi