相关疑难解决方法(0)

无法在ASP.NET Core 2.0中解析DbContext

首先,我正在尝试使用示例数据为我的数据库设定种子.我已经读过这是这样做的方法(在Startup.Configure中)(请参阅ASP.NET Core RC2种子数据库)

我正在使用ASP.NET Core 2.0和默认选项.

像往常一样,我注册了我DbContextConfigureServices.但在那之后,在Startup.Configure方法中,当我尝试使用GetRequiredService它解决它时,它抛出此消息:

System.InvalidOperationException:'无法从根提供程序解析作用域服务'SGDTP.Infrastructure.Context.SGDTPContext'.

我的Startup类是这样的:

public abstract class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<SGDTPContext>(options => options.UseInMemoryDatabase("MyDatabase"))
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();

        SeedDatabase(app);
    }

    private static void SeedDatabase(IApplicationBuilder app)
    {
        using (var context = app.ApplicationServices.GetRequiredService<SGDTPContext>())
        {
            // Seed the Database
            //... …
Run Code Online (Sandbox Code Playgroud)

.net c# asp.net entity-framework asp.net-core

32
推荐指数
1
解决办法
2万
查看次数

注入DbContext时无法访问ASP.NET Core中的已处置对象

在ASP.NET Core项目中,我在Startup上有以下内容:

  services.AddDbContext<Context>(x => x.UseSqlServer(connectionString));

  services.AddTransient<IValidationService, ValidationService>();

  services.AddTransient<IValidator<Model>, ModelValidator>();
Run Code Online (Sandbox Code Playgroud)

ValidationService如下:

public interface IValidationService {
    Task<List<Error>> ValidateAsync<T>(T model);
}

public class ValidationService : IValidationService {
    private readonly IServiceProvider _provider;

    public ValidationService(IServiceProvider provider) {
        _provider = provider;
    }

    public async Task<List<Error>> ValidateAsync<T>(T model) {
        IValidator<T> validator = _provider.GetRequiredService<IValidator<T>>();

        return await validator.ValidateAsync(model);
    }
}
Run Code Online (Sandbox Code Playgroud)

ModelValidator如下:

public class ModelValidator : AbstractValidator<Model> {
  public ModelValidator(Context context) {
    // Some code using context
  }
}
Run Code Online (Sandbox Code Playgroud)

当我在控制器中注入IValidationService并将其用作:

List<Error> errors = await _validator.ValidateAsync(order);    
Run Code Online (Sandbox Code Playgroud)

我收到错误:

System.ObjectDisposedException:无法访问已处置的对象.此错误的常见原因是处理从依赖项注入解析的上下文,然后尝试在应用程序的其他位置使用相同的上下文实例.如果您在上下文中调用Dispose()或将上下文包装在using语句中,则可能会发生这种情况.如果使用依赖项注入,则应该让依赖项注入容器负责处理上下文实例.对象名称:'上下文'.

知道为什么我在ModelValidator中使用Context时遇到此错误.

如何解决这个问题?

UPDATE …

entity-framework-core asp.net-core

20
推荐指数
4
解决办法
4万
查看次数

.NET 6如何在program.cs中自动运行迁移

在.Net 5中,我们可以通过将DataContext传递给Configure方法来调用迁移,并在启动类中调用迁移。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext dataContext)
{
    // migrate any database changes on startup (includes initial db creation)
    dataContext.Database.Migrate();

    ...
}
Run Code Online (Sandbox Code Playgroud)

我们如何在.Net 6 中做到这一点?

asp.net-core asp.net-core-6.0 .net-6.0

17
推荐指数
2
解决办法
2万
查看次数

How do I specify a schema for IdentityServer4 Entity Framework Core Migrations?

I am using IdentityServer4 2.0.2, and have followed the QuickStart tutorial to use Entity Framework Core. I am trying to change from the default schema (dbo) to a custom schema in SQL Server. The following code is working correctly, instructing the DbContexts to look for the tables in the "idsrv4" schema.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    var identityConnectionString = Configuration.GetConnectionString("Identity");
    var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

    services.AddIdentityServer()
        .AddDeveloperSigningCredential()
        .AddTestUsers(Config.GetUsers())
        .AddConfigurationStore(options =>
        {
            options.DefaultSchema = "idsrv4";
            options.ConfigureDbContext = builder => builder.UseSqlServer(identityConnectionString,
                sql …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core identityserver4 ef-core-2.0

5
推荐指数
1
解决办法
2957
查看次数

迁移 EF Core + ASP Identity + IdentityServer4 的问题

尝试使用 Asp Core Identity 和 EF Core 实现 IdentityServer 4。准确地说,本教程(根据需要在其之前完成):AspIdentity 与 EF Core

一切都很好,直到我必须运行迁移,这会引发错误:

An error occurred while calling method 'BuildWebHost' on class 'Program'. Continuing without the application service provider. Error: Invalid object name 'Clients'.
No DbContext named 'ConfigurationDbContext' was found.
Run Code Online (Sandbox Code Playgroud)

下面是完整的堆栈跟踪:

C:\CodeRepos\horrorServerCORE\IdentityProvider>dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using 'C:\Users\horror\AppData\Local\ASP.NET\DataProtection-Keys' as key repository and Windows DPAPI to encrypt keys at rest.
info: Microsoft.EntityFrameworkCore.Infrastructure[100403]
      Entity Framework Core 2.0.0-rtm-26452 initialized 'PersistedGrantDbContext' using …
Run Code Online (Sandbox Code Playgroud)

entity-framework-core asp.net-core identityserver4

4
推荐指数
1
解决办法
5889
查看次数