C# 尚未为Asp.netCore中的此DbContext for get方法配置任何数据库提供程序
我通过Asp.net core创建了一个web api项目,并向其中添加了一个api控制器(名称为C# 尚未为Asp.netCore中的此DbContext for get方法配置任何数据库提供程序,c#,asp.net-web-api,asp.net-core,entity-framework-core,C#,Asp.net Web Api,Asp.net Core,Entity Framework Core,我通过Asp.net core创建了一个web api项目,并向其中添加了一个api控制器(名称为BlogController),在blog controller中,我有一个get方法GetAllBlog,这是我的控制器: [Route("api/[controller]")] public class BlogController : Controller { private static Logger logger = LogManager.GetCurrentClassLogger
BlogController
),在blog controller中,我有一个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();
}
}
配置DbContext时
services.AddDbContext<Context>(options => options.UseSqlServer(connection));
正在创建一个新的上下文
,其配置与以前的配置完全不同
通过在如下启动过程中更改IContext
在DI框架中的注册方式
services.AddScoped<IContext, Context>();
您还应该显示添加db contextHow的配置以及将IContext映射到IoC的配置?你能发布它吗?这与你在添加IContext时创建的新选项有关IoC@Nkosi你的意思是什么?你能给我解释一下吗?好的,在我解释之前,让我们试一下。尝试
services.AddScoped()代码>并查看是否有效。
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; }
}
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.AddDbContext<Context>(options => options.UseSqlServer(connection));
services.AddScoped<IContext>(p => new Context(new DbContextOptions<Context>()));
services.AddScoped<IContext, Context>();
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();
}