我知道这个问题已被问了好几次,但我还没有得到我的解决方案呢。DotNet Core,没有数据库提供程序已配置此DbContext
我是DotNet Core中的新手。 我的问题是我想从我的表“标题”使用简单的LINQ命令选择数据,但我面临的错误。
其它信息:没有数据库提供商已经配置了 此的DbContext。可以通过覆盖 DbContext.OnConfiguring方法或使用 应用程序服务提供者上的AddDbContext来配置提供程序。如果使用AddDbContext,那么 也确保您的DbContext类型接受其构造函数 中的DbContextOptions对象,并将其传递给DbContext的基础构造函数。
我的控制器是。
public HeaderModel GetHeaderInformation()
{
using(var context = new ApplicationDbContext())
{
var header = context.Headers.Select(x => new HeaderModel
{
colorCode = x.colorCode,
height = x.height,
Id = x.Id,
left = x.left,
top = x.top,
width = x.width
}).FirstOrDefault();
return header;
}
}
我的ApplicationDbContext是。
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> //DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public ApplicationDbContext() : base()
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
public DbSet<Header> Headers { get; set; }
public DbSet<Menu> Menus { get; set; }
}
而我的startup.cs是。
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddApplicationInsightsTelemetry(Configuration);
services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
services.AddMvc();
感谢您的帮助。
感谢您的回复,我只是想在使用块中新建我的dbContext并使用它的DbSet <>来选择,添加和删除数据。你的解决方案很好,但它并没有解决我的问题。 –
如何将dbcontext注入到控制器类的构造函数中? – zuckerthoben
@zuckerthoben你有这个问题的答案[这里](https://stackoverflow.com/questions/37189984/dependency-injection-with-classes-other-than-a-controller-class):) – 5ar