2017-04-06 96 views
0

我知道这个问题已被问了好几次,但我还没有得到我的解决方案呢。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(); 

感谢您的帮助。

回答

6

您正在使用依赖注入。 services.AddDbContext负责为您创建一个DbContext对象。 使用该块没有意义,因为通过这样做,您将实例化一个没有连接字符串的新ApplicationDbContext。


写你的方法是这样的:

public HeaderModel GetHeaderInformation(ApplicationDbContext context) 
{ 
    // the code inside your using block 
} 

和.Net能够解决通过依赖注入的背景下。



此外,通常的做法是有作为的DbContext在构造函数类的私人只读属性附加伤害。所以你可能想要做这样的事情:

public class MyConroller : Controller 
{ 
    private readonly MyDbContext _context; 

    public MyConroller(MyDbContext ctx) 
    { 
     _context = ctx; 
    } 
} 

只是在你的方法中使用上下文属性。

+0

感谢您的回复,我只是想在使用块中新建我的dbContext并使用它的DbSet <>来选择,添加和删除数据。你的解决方案很好,但它并没有解决我的问题。 –

+0

如何将dbcontext注入到控制器类的构造函数中? – zuckerthoben

+0

@zuckerthoben你有这个问题的答案[这里](https://stackoverflow.com/questions/37189984/dependency-injection-with-classes-other-than-a-controller-class):) – 5ar

0

您应该移除无参数的构造函数,因为它可能是DI创建新实例时调用的构造函数。我知道对于一些人来说,这是问题,我希望它有帮助。

相关问题