Pomelo.EntityFrameworkCore.MySql
Pomelo.EntityFrameworkCore.MySql copied to clipboard
Could not scaffold the foreign key 'articleContent(articleId)'. A key for 'id' was not found in the principal entity type 'Articles'.
Steps to reproduce
Create Tables
DROP TABLE IF EXISTS `articles`;
CREATE TABLE `articles` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`keyId` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
`title` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
`description` varchar(500) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
`author` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
`publishStartTime` datetime(0) NULL DEFAULT NULL,
`publishEndTime` datetime(0) NULL DEFAULT NULL,
`urlParam` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL COMMENT,
`remark` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL COMMENT,
`createdTime` datetime(0) NULL DEFAULT NULL,
`updatedTime` datetime(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0),
PRIMARY KEY (`id`, `keyId`) USING BTREE,
INDEX `id`(`id`) USING BTREE,
INDEX `id_2`(`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Dynamic;
DROP TABLE IF EXISTS `articleContent`;
CREATE TABLE `articleContent` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`articleId` int(10) UNSIGNED NOT NULL,
`content` varchar(50000) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
INDEX `articleId_content`(`articleId`) USING BTREE,
CONSTRAINT `articleId_content` FOREIGN KEY (`articleId`) REFERENCES `articles` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
Use dbcontext scaffold
dotnet ef dbcontext scaffold "Server=localhost;Database=blogsite;User=root;Password=*****;TreatTinyAsBoolean=true;" "Pomelo.EntityFrameworkCore.MySql" --project MysqlAutoBuild.Main -f -o sakila
The issue
But Error
Could not scaffold the foreign key 'articleContent(articleId)'. A key for 'id' was not found in the principal entity type 'Articles'.
Further technical details
- Windows 10
- MySQL 5.7
- Microsoft.EntityFrameworkCore 3.1.11
- Microsoft.EntityFrameworkCore.Design 3.1.11
- Microsoft.EntityFrameworkCore.Tools 3.1.11
- Pomelo.EntityFrameworkCore.MySql 3.2.4
MySQL is installed via docker for windows 10
docker run \
-u root \
--name=mysql \
-d \
--restart=always \
-p 3306:3306 \
-e MYSQL_ROOT_PASSWORD=*******\
mysql:5.7
~~@SpiritLing Please post the entities involved (your C# model classes for articles and articleContent), the Fluent API definitions for the model classes (e.g. your Context.OnModelCreating() method), the LINQ query you are trying to execute and the failing SQL statement that gets generated (e.g. logged by EF Core).~~
@SpiritLing The issue for EF Core in your case is, that your articleContent table is referencing only part (the id column, but not the keyId column) of the primary key of the articles table.
EF Core can't therefore be sure, that the relationship is unique.
If your articleContent.id column is unique without the articleContent.keyId column (which it seems to be), make articleContent.id the single column PK. If you want to reference articleContent.keyId as well, make it a single column UNIQUE key (alternate key/AK).
@SpiritLing The issue for EF Core in your case is, that your
articleContenttable is referencing only part (theidcolumn, but not thekeyIdcolumn) of the primary key of thearticlestable. EF Core can't therefore be sure, that the relationship is unique.If your
articleContent.idcolumn is unique without thearticleContent.keyIdcolumn (which it seems to be), makearticleContent.idthe single column PK. If you want to referencearticleContent.keyIdas well, make it a single columnUNIQUEkey (alternate key/AK). `
@lauxjpn, I tried to do it with these two tables I have here, but it didn't work, even if I try to remove the ficha column from the primary key of the cad_processo table, it will still give a warning:
Could not scaffold the foreign key 'cad_alvara_fila_deposito_referencia(incidente)'. A key for 'incidente' was not found in the principal entity type 'CadProcesso'.
but if I leave it the ficha column as the primary key, two warnings are generated, this one above and one more for the incidente, what can I do in this case? I already tried to remove it from the primary key as you recommended in the @SpiritLing code, but it didn't work, I ran the queries that @SpiritLing left in the issue in my local database and it worked perfectly to remove the primary key, however in my queries it doesn't work
DROP TABLE IF EXISTS `cad_processo`;
CREATE TABLE `cad_processo` (
`ficha` int(6) NOT NULL AUTO_INCREMENT,
`incidente` smallint(6) NOT NULL DEFAULT '0',
`acesso_inicial` bit(1) DEFAULT NULL,
`alcada` decimal(10,2) DEFAULT NULL,
`arquivo` char(1) NOT NULL DEFAULT '',
`acao` varchar(8) DEFAULT NULL,
`andamento_nac` text,
`banca_advogado` int(11) DEFAULT NULL,
`bbb_parcela` int(11) DEFAULT NULL,
`bloqueio` char(1) DEFAULT '0',
`bloqueio_pendente` char(1) DEFAULT NULL,
`bdu` int(10) DEFAULT NULL,
`breve_relato` char(1) DEFAULT NULL,
`assunto` longtext CHARACTER SET utf8,
`calculado_por` int(11) DEFAULT NULL,
`calculo_contador` int(1) DEFAULT NULL,
`canal_encerramento` varchar(45) DEFAULT NULL,
`cod_Arquivo` int(6) DEFAULT '0',
`cod_arquivo_antigo` int(11) DEFAULT NULL,
`cod_Cli` int(5) DEFAULT '0',
`cod_cli_antigo` int(11) DEFAULT NULL,
`cod_motivo_desfecho` int(11) DEFAULT NULL,
`cod_motivo_escritorio` int(10) DEFAULT NULL,
`cod_pre_cadastro` int(11) DEFAULT NULL,
`cod_status_subsidios` int(11) DEFAULT '0',
`coligada` int(11) DEFAULT NULL,
`contratacao_revelia` char(1) DEFAULT '0',
`contratacao_execucao` char(1) DEFAULT '0',
`data_analise_enc` date DEFAULT NULL,
`data_atualizacao_analise_enc` datetime DEFAULT NULL,
`data_audiencia_civel` date DEFAULT NULL,
`data_citacao` date DEFAULT NULL,
`data_complemento_solicitado` datetime DEFAULT NULL,
`data_contratacao` date DEFAULT NULL,
`data_distribuicao` date DEFAULT NULL,
`data_encerramento` datetime DEFAULT NULL,
`data_encerramento_lex` date DEFAULT NULL,
`data_encerramento_judicial` datetime DEFAULT NULL,
`data_entrada_lex` date DEFAULT NULL,
`data_fase` datetime DEFAULT NULL,
`data_mandado_pagamento` date DEFAULT NULL,
`data_pa_itau` date DEFAULT NULL,
`data_pa_itau_2` datetime DEFAULT NULL,
`data_primeira_instancia` date DEFAULT NULL,
`data_processo_garantia` datetime DEFAULT NULL,
`data_protocolo` datetime DEFAULT NULL,
`data_pendente_ubb` datetime DEFAULT NULL,
`data_resultado_consolidado` datetime DEFAULT NULL,
`descredenciado` char(1) DEFAULT '0',
`descricao_tutela` text,
`desfecho` text,
`desfecho_cli_personalizado` varchar(75) DEFAULT NULL,
`documentos_faltaram` varchar(80) DEFAULT NULL,
`encerramento_judicial_pendente` int(11) DEFAULT '0',
`entrada` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`encerramento_sp` int(1) DEFAULT NULL,
`erro_cliente` char(2) DEFAULT NULL,
`estava_anexado_documentos` char(1) DEFAULT NULL,
`estava_conclusivo` char(1) DEFAULT NULL,
`estrategia` text,
`estrategia_itau_unibanco` char(1) DEFAULT NULL,
`enviado_estrategia` datetime DEFAULT NULL,
`existe_testemunha` bit(1) DEFAULT NULL,
`fase` smallint(6) DEFAULT NULL,
`fase_acordo_celebrado` char(5) DEFAULT NULL,
`filial_regional_banco` char(10) DEFAULT NULL,
`flag_andamento_pjur` char(1) DEFAULT '0',
`flag_contestacao` bit(1) DEFAULT NULL,
`flag_encerramento_itau_trabalhista` char(1) NOT NULL DEFAULT '0',
`flag_encerramento_pjur` int(1) DEFAULT '0',
`flag_encerramento_tj` char(1) DEFAULT '0' COMMENT 'verificação de encerramento do tj de toda base do escritorio independente de filas',
`flag_entrada_encerramento_tj` char(1) DEFAULT NULL,
`flag_estrategia_itau_trabalhista` char(1) DEFAULT '0',
`flag_estrategia_pjur` char(1) DEFAULT '0',
`flag_faturamento_itau_seguros` char(1) DEFAULT '0',
`flag_iseg_pjur` char(1) DEFAULT '0',
`flag_meta_estrategia_pjur` char(1) DEFAULT '0',
`flag_nm` char(1) DEFAULT NULL,
`flag_obrigacao_fazer` char(1) DEFAULT '0',
`flag_pagamento_pjur` char(1) DEFAULT '0',
`flag_pagamento_verba_pjur` char(1) DEFAULT '0',
`generica` bit(1) DEFAULT NULL,
`gerencia_cont_lex` char(10) DEFAULT NULL,
`gerencia_enc_lex` char(10) DEFAULT NULL,
`grau_acompanhamento` int(11) DEFAULT NULL,
`grau_acompanhamento_justificativa` text,
`grau_risco` smallint(6) DEFAULT '0',
`guid` varchar(20) DEFAULT NULL,
`hash` bigint(20) DEFAULT NULL,
`ha_risco_acordo` char(1) DEFAULT NULL,
`honorario_exito` char(1) DEFAULT NULL,
`inc_processo_relacionado` char(1) DEFAULT '0',
`indisponivel_em` date DEFAULT NULL,
`jurisprudencia` char(1) DEFAULT NULL,
`juizo` varchar(5) NOT NULL DEFAULT '',
`justificativa` text,
`laudos_subsidios` char(1) DEFAULT NULL,
`mandado_pagamento_pendente` char(1) DEFAULT NULL,
`materia` smallint(6) DEFAULT '0',
`megabonus_encerramento` int(1) DEFAULT NULL,
`migracao` varchar(305) DEFAULT NULL,
`motivo` int(11) DEFAULT '0',
`motivo_encerramento_honorarios` text,
`motivo_outro` int(11) DEFAULT NULL,
`multa` varchar(200) DEFAULT '0',
`negativacao` char(2) DEFAULT NULL,
`negativacao_corrigida` char(2) DEFAULT NULL,
`nome_vendedor` varchar(205) DEFAULT NULL,
`numero_integracao` varchar(50) DEFAULT NULL,
`numero_processo` varchar(50) DEFAULT NULL,
`numero_processo_cnj` varchar(35) DEFAULT ' ',
`numero_processo_cnj_pesq` varchar(35) DEFAULT ' ',
`numero_processo_pesq` varchar(50) DEFAULT NULL,
`obf_estrategia_itau_unibanco` char(1) DEFAULT NULL,
`objeto_demanda` int(11) DEFAULT NULL,
`obrigacao_fazer` char(1) DEFAULT NULL,
`obsdesfecho` text,
`observacao_processo` text,
`observacao_status_subsidios` text,
`obs_situacao_administrativa` text,
`oj_numero` smallint(6) DEFAULT '0',
`oj_sigla` char(10) DEFAULT NULL,
`pa_primeira_instancia` varchar(70) DEFAULT NULL,
`pa_primeira_instancia_2` varchar(70) DEFAULT NULL,
`pasta_morto` varchar(45) DEFAULT NULL,
`pedido` int(11) DEFAULT '0',
`pedido_tutela` bit(1) DEFAULT NULL,
`pend_etiq` int(9) DEFAULT '0',
`prazo_impugnar` char(1) DEFAULT '0',
`primeiro_autor` int(11) DEFAULT NULL,
`primeiro_reu` int(11) DEFAULT NULL,
`problema_corrigido` char(2) DEFAULT NULL,
`processo_eletronico` char(1) DEFAULT '0',
`processo_garantia_pendente` int(11) DEFAULT NULL,
`prognostico_itau` varchar(45) DEFAULT NULL,
`provisao_gerencial` decimal(20,2) DEFAULT NULL,
`ramo_cec` varchar(45) DEFAULT NULL,
`recebimento_laudos` char(1) DEFAULT NULL,
`regiao_turma` int(11) DEFAULT NULL,
`reiteracao` int(11) DEFAULT NULL,
`resultado_consolidado` varchar(85) DEFAULT NULL,
`resultado_primeira_instancia` text,
`risco_acordo` decimal(10,2) DEFAULT NULL,
`risco_cliente` int(11) DEFAULT '0',
`risco_favor_banco` char(1) DEFAULT NULL,
`rito` int(11) DEFAULT NULL,
`solicitou_calculo` int(11) DEFAULT NULL,
`status_acordo_santander` char(1) DEFAULT NULL,
`status_analise_enc` int(11) DEFAULT NULL,
`status_analise_enc_tim` int(11) DEFAULT NULL,
`status_of` int(1) DEFAULT NULL,
`status_tj` varchar(10) DEFAULT NULL,
`subsidios_utilizados` char(2) DEFAULT NULL,
`sub_motivo` int(11) DEFAULT NULL,
`tarefas_nm` char(1) DEFAULT NULL,
`tem_status_subsidios` int(11) DEFAULT NULL,
`tempo_negativacao` char(1) DEFAULT NULL,
`tempo_negativacao_corrigida` char(1) DEFAULT NULL,
`tempo_problema_corrigido` char(1) DEFAULT NULL,
`tipo_servico` varchar(55) DEFAULT NULL COMMENT 'Diligência, Acompanhamento ou Patrocionio.',
`tutela` int(11) DEFAULT NULL,
`tutela_cumprida` bit(1) DEFAULT NULL,
`tutela_deferida` bit(1) DEFAULT NULL,
`update_usuario` smallint(6) NOT NULL DEFAULT '0',
`usuario_contestacao` int(10) DEFAULT NULL,
`usuario_pa_itau` varchar(11) DEFAULT NULL,
`usuario_pa_itau_2` varchar(65) DEFAULT NULL,
`valor_atualizado_encerramento` decimal(20,2) DEFAULT '0.00',
`valor_autor` decimal(10,2) DEFAULT NULL,
`valor_causa` decimal(28,2) DEFAULT '0.00',
`valor_deposito` decimal(10,2) DEFAULT NULL,
`valor_estimado` decimal(28,2) DEFAULT '0.00',
`valor_mandado_pagamento` decimal(20,2) DEFAULT NULL,
`valor_multa` varchar(200) DEFAULT '0.00',
`valor_mundicalc` decimal(20,2) DEFAULT NULL,
`valor_pago` decimal(20,2) DEFAULT '0.00',
`valor_protocolo` decimal(20,2) DEFAULT NULL,
`valor_resultado_consolidado` decimal(20,2) DEFAULT NULL,
`v_causa` decimal(20,2) DEFAULT '0.00',
`v_estimado` decimal(20,2) DEFAULT '0.00',
`v_provisao` decimal(20,2) DEFAULT '0.00',
`v_risco` decimal(20,2) DEFAULT '0.00',
`data_status_atual` datetime DEFAULT NULL,
`revogada` char(1) DEFAULT '0',
`litigancia_ma_fe` char(1) DEFAULT '0',
`personagem_litigancia` char(1) DEFAULT NULL,
`justica_gratuita` char(1) DEFAULT '0',
PRIMARY KEY (`ficha`,`incidente`) USING BTREE,
KEY `novoarq` (`cod_Arquivo`,`cod_Cli`),
KEY `ficha` (`ficha`),
KEY `incidente` (`incidente`),
KEY `arquivo` (`arquivo`),
KEY `reu` (`primeiro_reu`),
KEY `autor` (`primeiro_autor`),
KEY `hash` (`hash`),
KEY `cli` (`cod_Cli`),
KEY `juizo` (`juizo`),
KEY `cnj` (`numero_processo_cnj`,`numero_processo_cnj_pesq`),
KEY `cad_processo_k2` (`arquivo`,`numero_processo_pesq`,`juizo`,`acao`,`oj_numero`,`oj_sigla`,`numero_processo_cnj_pesq`) USING BTREE,
KEY `cad_processo_k3` (`arquivo`,`ficha`,`incidente`),
KEY `cad_processo_k1` (`arquivo`,`numero_integracao`),
KEY `numero_processo` (`numero_processo`),
KEY `numero_processo_cnj` (`numero_processo_cnj`),
KEY `inc_relacionado` (`inc_processo_relacionado`),
KEY `numero_integracao` (`numero_integracao`),
KEY `numero_processo_cnj_pesq` (`numero_processo_cnj_pesq`),
KEY `numero_processo_pesq` (`numero_processo_pesq`),
KEY `cod_pre_cadastro` (`cod_pre_cadastro`),
KEY `status_analise_enc` (`status_analise_enc`),
KEY `fk_cod_motivo_desfecho_mc_idx` (`cod_motivo_desfecho`),
KEY `sub_motivo` (`sub_motivo`),
KEY `flag_obrigacao_fazer` (`flag_obrigacao_fazer`),
KEY `grau_acompanhamento` (`grau_acompanhamento`),
KEY `acao` (`acao`),
KEY `descredenciado` (`descredenciado`),
KEY `risco_cliente` (`risco_cliente`),
KEY `tipo_servico` (`tipo_servico`),
KEY `processo_eletronico` (`processo_eletronico`),
KEY `tutela` (`tutela`),
KEY `rito` (`rito`),
KEY `oj_sigla` (`oj_sigla`),
KEY `motivo` (`motivo`),
KEY `grau_risco` (`grau_risco`),
KEY `fase` (`fase`),
KEY `estrategia_itau_unibanco` (`estrategia_itau_unibanco`),
KEY `entrada` (`entrada`),
KEY `data_fase` (`data_fase`),
KEY `migracao` (`migracao`),
KEY `data_contratacao` (`data_contratacao`),
KEY `data_distribuicao` (`data_distribuicao`),
KEY `data_citacao` (`data_citacao`),
KEY `data_resultado_consolidado` (`data_resultado_consolidado`),
KEY `oj_numero` (`oj_numero`)
) ENGINE=InnoDB AUTO_INCREMENT=1087775 DEFAULT CHARSET=latin1 COMMENT='Todos os dados dos processos estão armazenados aqui';
DROP TABLE IF EXISTS `cad_alvara_fila_deposito_referencia`;
CREATE TABLE `cad_alvara_fila_deposito_referencia` (
`codigo` int(11) NOT NULL AUTO_INCREMENT,
`ficha` int(11) DEFAULT NULL,
`incidente` smallint(6) DEFAULT NULL,
`ordem_obrigacao` int(11) DEFAULT NULL,
`tipo_obrigacao` varchar(200) DEFAULT NULL,
`valor_liberado` decimal(10,2) DEFAULT NULL,
`valor_pago` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`codigo`),
KEY `fk_ficha_idx` (`ficha`),
KEY `fk_incidente_idx` (`incidente`),
CONSTRAINT `fk_ficha` FOREIGN KEY (`ficha`) REFERENCES `cad_processo` (`ficha`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_incidente` FOREIGN KEY (`incidente`) REFERENCES `cad_processo` (`incidente`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=2369 DEFAULT CHARSET=latin1;