Não foi possível criar um objeto do tipo 'MyEFCoreDbContext' xaf Blazor EFCore

Nov 24 2020

Eu criei um novo projeto com o assistente XAF Blazor 20.2.3 e atualizei os pacotes EFCore para 5.0.
Na PM eu corri

Install-Package Microsoft.EntityFrameworkCore.Tools

Porém quando eu corro

add-migration initial

eu recebo

Não foi possível criar um objeto do tipo 'ExamBuddyEFCoreDbContext'. Para os diferentes padrões suportados em tempo de design, consultehttps://go.microsoft.com/fwlink/?linkid=851728

Eu olhei o link, mas não acho que se aplique ao aplicativo xaf Blazor.

Tentei comentar o Inicializador de banco de dados

using System;
using DevExpress.ExpressApp.EFCore.Updating;
using Microsoft.EntityFrameworkCore;
using DevExpress.Persistent.BaseImpl.EF.PermissionPolicy;
using DevExpress.Persistent.BaseImpl.EF;
using DevExpress.ExpressApp.Design;
using DevExpress.ExpressApp.EFCore.DesignTime;
using DevExpress.Persistent.Base;
namespace ExamBuddy.Module.BusinessObjects {
    public class ExamBuddyContextInitializer : DbContextTypesInfoInitializerBase {
        protected override DbContext CreateDbContext() {
            var builder = new DbContextOptionsBuilder<ExamBuddyEFCoreDbContext>()
                .UseSqlServer(@";");
            return new ExamBuddyEFCoreDbContext(builder.Options);
        }
    }
    //[TypesInfoInitializer(typeof(ExamBuddyContextInitializer))]
    public class ExamBuddyEFCoreDbContext : DbContext {
        public ExamBuddyEFCoreDbContext(DbContextOptions<ExamBuddyEFCoreDbContext> options) : base(options) {
        }
        public DbSet<ModuleInfo> ModulesInfo { get; set; }
        public DbSet<ModelDifference> ModelDifferences { get; set; }
        public DbSet<ModelDifferenceAspect> ModelDifferenceAspects { get; set; }
        public DbSet<PermissionPolicyRole> Roles { get; set; }
        public DbSet<PermissionPolicyRoleBase> RolesBase { get; set; }
        public DbSet<PermissionPolicyUser> Users { get; set; }
        public DbSet<CourseUnit> CourseUnits { get; set; }
         
    }

[Atualizar]

Eu defini o projeto do módulo para ser o projeto inicial, então executei

add-migration initial -verbose

o resultado foi

O projeto de inicialização 'ExamBuddy.Module' visa a estrutura '.NETStandard'. Não há tempo de execução associado a esta estrutura e os projetos que visam a ela não podem ser executados diretamente. Para usar as Ferramentas do Console do Entity Framework Core Package Manager com este projeto, adicione um projeto executável direcionado ao .NET Framework ou .NET Core que faça referência a este projeto e defina-o como o projeto de inicialização; ou atualize este projeto para o .NET Framework ou .NET Core de destino cruzado. Para obter mais informações sobre como usar o EF Core Tools com projetos .NET Standard, consultehttps://go.microsoft.com/fwlink/?linkid=2034705

[Atualizar]

Cross linking para o tíquete Dev Express

Eu adicionei o seguinte ao ExamBuddy.Blazor.Server

    public class ExamBuddyContextFactory : IDesignTimeDbContextFactory<ExamBuddyEFCoreDbContext>
    {
        public ExamBuddyEFCoreDbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<ExamBuddyEFCoreDbContext>();
            optionsBuilder.UseSqlServer(@"Integrated Security=SSPI;MultipleActiveResultSets=true;Pooling=false;Data Source=(localdb)\\mssqllocaldb;Initial Catalog=ExamBuddy;ConnectRetryCount=0;");
            return new ExamBuddyEFCoreDbContext(optionsBuilder.Options);
        }
    }

Experimentando no console do gerenciador de pacotes e adicionando o ConsoleApp1 que tenho

PM> add-migration init
Build started...
Build succeeded.
Startup project 'ExamBuddy.Module' targets framework '.NETStandard'. There is no runtime associated with this framework, and projects targeting it cannot be executed directly. To use the Entity Framework Core Package Manager Console Tools with this project, add an executable project targeting .NET Framework or .NET Core that references this project, and set it as the startup project; or, update this project to cross-target .NET Framework or .NET Core. For more information on using the EF Core Tools with .NET Standard projects, see https://go.microsoft.com/fwlink/?linkid=2034705

Então, adicionei ConsoleApp1 como um projeto de inicialização principal 3.1 .net e adicionei referências aos projetos XAF

PM> add-migration init
Build started...
Build succeeded.
Unable to create an object of type 'ExamBuddyEFCoreDbContext'. 

Para os diferentes padrões suportados em tempo de design, consulte https://go.microsoft.com/fwlink/?linkid=851728

A fonte está no GitHub

Respostas

1 KirstenGreed Nov 30 2020 at 15:37

Criei a classe ExamBuddyContextFactory conforme recomendado no tíquete DevExpress no projeto do Módulo e, então, fui capaz de criar a migração inicial.

public class ExamBuddyContextFactory : IDesignTimeDbContextFactory<ExamBuddyEFCoreDbContext>
{
    public ExamBuddyEFCoreDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<ExamBuddyEFCoreDbContext>();
        optionsBuilder.UseSqlServer(@"Integrated Security=SSPI;MultipleActiveResultSets=true;Pooling=false;Data Source=(localdb)\\mssqllocaldb;Initial Catalog=ExamBuddy;ConnectRetryCount=0;");
        return new ExamBuddyEFCoreDbContext(optionsBuilder.Options);
    }
}