【发布时间】:2019-10-09 22:13:27
【问题描述】:
我正在使用 if core 将数据插入到 .net core 中的数据库中,我能够从 get API 获取数据,但是当我将数据插入到数据库中时出现错误。并且它在 Context 出现编译错误。
错误 InvalidOperationException:没有为此 DbContext 配置数据库提供程序。可以通过覆盖 DbContext 来配置提供程序。在配置方法上或通过在应用程序服务提供者上使用 AddDbContext。如果使用了 AddDbContext,那么还要确保您的 DbContext 类型在其构造函数中接受 DbContextOptions 对象并将其传递给 DbContext 的基本构造函数。
上下文类
public class Context : DbContext
{
public Context(DbContextOptions<Context> options) : base(options)
{
}
public DbSet<Mplus> MpData { get; set; }
}
API控制器
namespace MplusApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class MPlusController : ControllerBase
{
private Context _context;
public MPlusController(Context context) {
_context = context;
}
[HttpGet("{Ftemp}")]
public IActionResult Get(int Ftemp) {
using (var context = new Context())//Getting compilation error here
{
var mp = new Mplus()
{
Ftemp = Ftemp,
};
context.MpData.Add(mp);
context.SaveChanges();
}
return Ok();
}
}
型号
public class Mplus
{
public int Ftemp { get; set; }
}
startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<Context>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
【问题讨论】:
标签: .net model-view-controller entity-framework-core