【问题标题】:A provider can be configured by overriding the DbContext.OnConfiguring可以通过覆盖 DbContext.OnConfiguring 来配置提供程序
【发布时间】:2018-12-03 17:11:37
【问题描述】:

由于某种原因,因为我添加了一个应用程序用户类,它说我有两个我没有的上下文,但我按照它所说的那样创建了这个类:

public class ApplicationDbContextFactory : IDbContextFactory<solitudeDContext>
    {
        public solitudeDContext Create(DbContextFactoryOptions options)
        {
            var optionsBuilder = new DbContextOptionsBuilder<solitudeDContext>();
            return new solitudeDContext(optionsBuilder.Options);
        }
    }
}

但现在它说的是:

没有为此 DbContext 配置数据库提供程序。一个 可以通过覆盖 DbContext.OnConfiguring 来配置提供程序 方法或通过在应用程序服务提供者上使用 AddDbContext。 如果使用了 AddDbContext,那么还要确保你的 DbContext 类型 在其构造函数中接受一个 DbContextOptions 对象,并且 将其传递给 DbContext 的基本构造函数。

这是我的数据库上下文层:

public class solitudeDContext : IdentityDbContext<IdentityUser>
    {  public solitudeDContext(DbContextOptions<solitudeDContext> options) : base(options)
        {
        }
        public DbSet<basketheader> BasketHeader { get; set; }
        public DbSet<basketlines> BasketLines { get; set; }
        public DbSet<customer> Customer { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            builder.Entity<ApplicationUser>(entity =>
            {
                entity.ToTable(name: "AspNetUser", schema: "Security");
                entity.Property(e => e.Id).HasColumnName("AspNetUserId");

            });

        }
    }

有人知道这里是什么吗?我正在使用 ASP.NET CORE 1.1。在我使用我自己的应用程序用户身份之前,这编译得很好。所以我把它附在下面,以防那里有问题。

public  class ApplicationUser: IdentityUser
{
        public string FirstName { get; set; }
        public string LastName{ get; set; }
        public DateTime dob { get; set; }
}

我的startup.cs

 // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
        services.AddDbContext<IdentityDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),b=>b.MigrationsAssembly("solitudeeccore")));
        services.AddIdentity<IdentityUser, IdentityRole>()
   .AddEntityFrameworkStores<IdentityDbContext>()
   .AddDefaultTokenProviders();
        services.AddTransient<IMessageService, FileMessageService>();
        services.AddAuthentication();            
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();                
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();
        app.UseIdentity();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });


    }

我唯一的猜测是,现在因为我使用的是应用程序用户身份,所以用户在制作 donet 编译器时会考虑两个上下文?

【问题讨论】:

  • 在你的工厂类中添加一个提供者到 DbContextOptionsBuilder 像 optionsBuilder.UseSqlServer(....) 然后调用 optionBuilder.Build()
  • 如果您使用IDbContextFactory,那么您需要在那里配置提供程序,因为设计时服务将首先使用它。如果您想在ConfigureServices 中配置提供程序,请删除IDbContextFactory 实现。

标签: c# asp.net asp.net-core


【解决方案1】:

我建议您通过添加 IDesignTimeDbContextFactory 实现来解决此问题。

// TODO: Remove.
// (part of the workaround for https://github.com/aspnet/EntityFramework/issues/5320)
public class TemporaryDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
    public ApplicationDbContext CreateDbContext(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .Build();

        var builder = new DbContextOptionsBuilder<ApplicationDbContext>();

        var connectionString = configuration.GetConnectionString("DefaultConnection");

        builder.UseSqlServer(connectionString);

        // Stop client query evaluation
        builder.ConfigureWarnings(w => 
            w.Throw(RelationalEventId.QueryClientEvaluationWarning));

        return new ApplicationDbContext(builder.Options);
    }
}

【讨论】:

  • 如何访问 TemporaryDbContextFactory 中的 IHostingEnironment 以加载 appsettings.development.json?
猜你喜欢
  • 2012-02-16
  • 2020-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-15
  • 2012-11-16
  • 1970-01-01
  • 2016-02-15
相关资源
最近更新 更多