DBContext потерян после обновления EF Core с 5 до 9C#

Место общения программистов C#
Anonymous
 DBContext потерян после обновления EF Core с 5 до 9

Сообщение Anonymous »

Мы уже давно используем EF Core 5 в нескольких приложениях, но у нас никогда не было времени обновлять, также из -за зависимостей. < /p>
Но теперь мы Обновили его, почти не было обновлений необходимого кода. Локально в Visual Studio нет проблем. Но после развертывания мы столкнулись с проблемой. Сначала не возникает проблем, веб -сайт работает и работает, мы можем получить доступ к базе данных. /p>

system.invalidoperationexception: Поставщик базы данных не был настроен для этого dbcontext. Поставщик может быть настроен, переопределяя метод «dbcontext.onconfiguring» или с помощью «AddDBContext» на поставщике услуг приложений. Если используется 'AddDBContext', то также убедитесь, что ваш тип dbContext принимает объект dbContextOptions в своем конструкторе и передает его базовому конструктору для dbContext. .Initialize (iServiceProvider ScopedProvider, DBContextOptions ContextOptions, Контекст dbcontext)

at microsoft.entityframeworkcore.dbcontext.get_contextservices ()

at microsoft.entityframeworkcore.dbcontext.get_model ()

at microsoft. EntityFrameWorkCore.Internal.Internaldbset

Код: Выделить всё

1.get_EntityType()   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet< /code> 1.checkstate ()

at microsoft.entityframeworkcore.internal.internaldbset1.get_EntityQueryable()   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet< /code> 1.system.collections.generic.iasyncenumerable.getAsyncenumerator (CancellationToken CancellationToken)1.GetAsyncEnumerator()   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable< /code> 1 Источник, CancellationToken CancellationToken)

at beeer.services.dashboard.dashboardservice.getMaxDaysFromSettings () в D: \ Agents \ Agent.Morpheus_work \ 2 \ S \ Back-End \ Beeeer. Services \ Dashboard \ Dashboardservice.cs: строка 330

at Beeeer.services.dashboard.dashbordservice.getRecentErrorlogs (пейджинг-пейджин > в Beeeer.api.controllers.dashboardController.getRecentErrorlogs (пейджинговая пейджинг) в D: \ Agents \ Agent.morpheus_work \ 2 \ S \ Back-End \ Beeeer.api \ Controllers \ DashboardController.cs: Строка 99

at lambda_method62 (закрытие, объект)

at Microsoft.aspnetcore.mvc.infrastructure.actionmethodexecutor.awaitableobjectresultexecutor.execute (ActionContext ActionContext, iActionResulttyPemapper Mapper, EbjectMethodexeCutor Executor, объектный контроллер, объект [] аргументы)
at at at at at at at at at at at at at at at at at at at at at Microsoft.aspnetcore.mvc.infrastructure.controllerActionInvoker.g__awaited | 12_0 (ControllerActionInvoker Invoker, ValueTask`1 ActionResultValuetSk)

at microsoft.aspnetcore.mvc.infrastructure.controlleractionInvoker.g__waTecaitEd LastTask, State Next, Scope Scope, состояние объекта, Boolean Iscompleted) < /p>
< /blockquote>
Соответствующий код: < /p>
public static class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

private static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment.EnvironmentName;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
config.AddJsonFile($"appsettings.{env}.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();

if (args != null)
{
config.AddCommandLine(args);
}
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
})
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
.ReadFrom.AppSettings().Enrich.FromLogContext());
}
< /code>
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)
{
var connectionString = Configuration["AppSettings:ConnectionString"];
services.AddDbContext(options => options.UseOracle(connectionString));

// ....
}
}
< /code>
public class MyContext : DbContext
{
public MyContext()
{
}

public MyContext(DbContextOptions options)
: base(options)
{
}

public virtual DbSet SenderSettings { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
}
}
< /code>
Некоторые руководства, что делать дальше, будет оценено. p>
@jeff Zola: Да, мы проверили заметки о выпуске. Но ничто не могло объяснить, в чем была вызвана проблема. Опция добавить Encrypt = false 
к строке подключения не является действительной для баз данных Oracle.
@jalpal panchal: конструктор без параметра не является проблемой, я попробовал это но нет успеха. < /p>
Я сделал обновления для пакетов Devart и EF: < /p>

от EF 5 до EF 6: Нет проблемы < /li>
От EF 6 до EF 7: Нет проблемы < /li>
от EF 7 до EF 8: Нет проблемы < /li>
От EF 8 до EF 9: Хьюстон у нас есть проблема .... < /li>
< /ul>
Обновление проекта от .net 8 до .net 9 решил проблему, после этого обновления я также мог обновить Ef и devart.
Но все равно спасибо за ваши предложения!

Подробнее здесь: https://stackoverflow.com/questions/794 ... rom-5-to-9

Вернуться в «C#»