655 messaggi dal 18 febbraio 2002
www.dimsolutions.it

E' normale se la tabella non esiste. Tu come la vuoi chiamare la tabella degli utenti?
Stai usando l'approccio code first o database first?


Per il momento un nome vale l'altro giusto per capire facciamo "NomeTabellaUtenti"
L'esempio http://www.aspitalia.com/articoli/asp.net-core/personalizzare--aspnet-core-identity.aspx
quale approccio usa? credo "code first" perchè quando eseguo il codice vengono create le tabelle sul db

Telesoccorso Lineaperta: Servizi di Telesoccorso
11.382 messaggi dal 09 febbraio 2002
Contributi

credo "code first" perchè quando eseguo il codice vengono create le tabelle sul db

Esatto, quindi dopo aver aggiunto la chiamata al .ToTable("NomeTabellaUtenti"), aggiungi ed esegui una migration in questo modo:

dotnet ef migrations add "RenamedUserTable"
dotnet ef database update


ciao,
Moreno
Modificato da BrightSoul il 09 gennaio 2019 09.21 -

Enjoy learning and just keep making
655 messaggi dal 18 febbraio 2002
www.dimsolutions.it
Ho creato la migrazione e aggiornato con i comandi che mi hai indicato.

Quando lo eseguo mi dice che la tabella "nometabellautenti" non esiste.
Se creo manualmente la tabella "nometabellautenti" sul database con i relativi campi funziona correttamente.

Non mi è tanto chiaro... ma non dovrebbe crearla ef la tabella?

Telesoccorso Lineaperta: Servizi di Telesoccorso
11.382 messaggi dal 09 febbraio 2002
Contributi

Non mi è tanto chiaro... ma non dovrebbe crearla ef la tabella?

Teoricamente sì, che sia una limitazione del provider di MySql? Creando la migration ti è stato aggiunto un file .cs al progetto che porta il nome della migration. Cosa c'è dentro il suo metodo Up?

Enjoy learning and just keep making
655 messaggi dal 18 febbraio 2002
www.dimsolutions.it

Teoricamente sì, che sia una limitazione del provider di MySql? Creando la migration ti è stato aggiunto un file .cs al progetto che porta il nome della migration. Cosa c'è dentro il suo metodo Up?



public partial class RenamedUserTable : Migration


        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropForeignKey(
                name: "FK_AspNetUserClaims_AspNetUsers_UserId",
                table: "AspNetUserClaims");

            migrationBuilder.DropForeignKey(
                name: "FK_AspNetUserLogins_AspNetUsers_UserId",
                table: "AspNetUserLogins");

            migrationBuilder.DropForeignKey(
                name: "FK_AspNetUserRoles_AspNetUsers_UserId",
                table: "AspNetUserRoles");

            migrationBuilder.DropForeignKey(
                name: "FK_AspNetUserTokens_AspNetUsers_UserId",
                table: "AspNetUserTokens");

            migrationBuilder.DropForeignKey(
                name: "FK_UserAddresses_AspNetUsers_UserId",
                table: "UserAddresses");

            migrationBuilder.DropPrimaryKey(
                name: "PK_AspNetUsers",
                table: "AspNetUsers");

            migrationBuilder.RenameTable(
                name: "AspNetUsers",
                newName: "NomeTabellaUtenti");

            migrationBuilder.AddPrimaryKey(
                name: "PK_NomeTabellaUtenti",
                table: "NomeTabellaUtenti",
                column: "Id");

            migrationBuilder.AddForeignKey(
                name: "FK_AspNetUserClaims_NomeTabellaUtenti_UserId",
                table: "AspNetUserClaims",
                column: "UserId",
                principalTable: "NomeTabellaUtenti",
                principalColumn: "Id",
                onDelete: ReferentialAction.Cascade);

            migrationBuilder.AddForeignKey(
                name: "FK_AspNetUserLogins_NomeTabellaUtenti_UserId",
                table: "AspNetUserLogins",
                column: "UserId",
                principalTable: "NomeTabellaUtenti",
                principalColumn: "Id",
                onDelete: ReferentialAction.Cascade);

            migrationBuilder.AddForeignKey(
                name: "FK_AspNetUserRoles_NomeTabellaUtenti_UserId",
                table: "AspNetUserRoles",
                column: "UserId",
                principalTable: "NomeTabellaUtenti",
                principalColumn: "Id",
                onDelete: ReferentialAction.Cascade);

            migrationBuilder.AddForeignKey(
                name: "FK_AspNetUserTokens_NomeTabellaUtenti_UserId",
                table: "AspNetUserTokens",
                column: "UserId",
                principalTable: "NomeTabellaUtenti",
                principalColumn: "Id",
                onDelete: ReferentialAction.Cascade);

            migrationBuilder.AddForeignKey(
                name: "FK_UserAddresses_NomeTabellaUtenti_UserId",
                table: "UserAddresses",
                column: "UserId",
                principalTable: "NomeTabellaUtenti",
                principalColumn: "Id",
                onDelete: ReferentialAction.Cascade);
        }

Telesoccorso Lineaperta: Servizi di Telesoccorso
11.382 messaggi dal 09 febbraio 2002
Contributi
Ok, sembra che la migration sia stata generata correttamente, infatti lì in mezzo si trova l'istruzione che serve a rinominare la tabella.
 migrationBuilder.RenameTable(
                name: "AspNetUsers",
                newName: "NomeTabellaUtenti");


Che output ottieni quando lanci questo? Il comando si completa correttamente o ci sono errori?
dotnet ef database update


Quale provider di MySql stai usando? Quelli prodotti da Oracle o quelli di Pomelo?
https://www.nuget.org/packages/Pomelo.EntityFrameworkCore.MySql

ciao,
Moreno

Enjoy learning and just keep making
655 messaggi dal 18 febbraio 2002
www.dimsolutions.it

Che output ottieni quando lanci questo? Il comando si completa correttamente o ci sono errori?
dotnet ef database update



PM> dotnet ef database update
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 2.2.0-rtm-35687 initialized 'ApplicationDbContext' using provider 'Pomelo.EntityFrameworkCore.MySql' with options: MaxPoolSize=128 ServerVersion 5.6.37 MySql 
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (11ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='aspidentitymysql' AND TABLE_NAME='__EFMigrationsHistory';
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (15ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE `__EFMigrationsHistory` (
          `MigrationId` varchar(95) NOT NULL,
          `ProductVersion` varchar(32) NOT NULL,
          CONSTRAINT `PK___EFMigrationsHistory` PRIMARY KEY (`MigrationId`)
      );
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (14ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='aspidentitymysql' AND TABLE_NAME='__EFMigrationsHistory';
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (2ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT `MigrationId`, `ProductVersion`
      FROM `__EFMigrationsHistory`
      ORDER BY `MigrationId`;
info: Microsoft.EntityFrameworkCore.Migrations[20402]
      Applying migration '00000000000000_CreateIdentitySchema'.
Applying migration '00000000000000_CreateIdentitySchema'.
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (18ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE `AspNetRoles` (
          `Id` varchar(95) NOT NULL,
          `Name` varchar(256) NULL,
          `NormalizedName` varchar(256) NULL,
          `ConcurrencyStamp` longtext NULL,
          CONSTRAINT `PK_AspNetRoles` PRIMARY KEY (`Id`)
      );
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (16ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE `AspNetUsers` (
          `Id` varchar(95) NOT NULL,
          `UserName` varchar(256) NULL,
          `NormalizedUserName` varchar(256) NULL,
          `Email` varchar(256) NULL,
          `NormalizedEmail` varchar(256) NULL,
          `EmailConfirmed` bit NOT NULL,
          `PasswordHash` longtext NULL,
          `SecurityStamp` longtext NULL,
          `ConcurrencyStamp` longtext NULL,
          `PhoneNumber` longtext NULL,
          `PhoneNumberConfirmed` bit NOT NULL,
          `TwoFactorEnabled` bit NOT NULL,
          `LockoutEnd` datetime(6) NULL,
          `LockoutEnabled` bit NOT NULL,
          `AccessFailedCount` int NOT NULL,
          CONSTRAINT `PK_AspNetUsers` PRIMARY KEY (`Id`)
      );
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (17ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE `AspNetRoleClaims` (
          `Id` int NOT NULL,
          `RoleId` varchar(95) NOT NULL,
          `ClaimType` longtext NULL,
          `ClaimValue` longtext NULL,
          CONSTRAINT `PK_AspNetRoleClaims` PRIMARY KEY (`Id`),
          CONSTRAINT `FK_AspNetRoleClaims_AspNetRoles_RoleId` FOREIGN KEY (`RoleId`) REFERENCES `AspNetRoles` (`Id`) ON DELETE CASCADE
      );
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (18ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE `AspNetUserClaims` (
          `Id` int NOT NULL,
          `UserId` varchar(95) NOT NULL,
          `ClaimType` longtext NULL,
          `ClaimValue` longtext NULL,
          CONSTRAINT `PK_AspNetUserClaims` PRIMARY KEY (`Id`),
          CONSTRAINT `FK_AspNetUserClaims_AspNetUsers_UserId` FOREIGN KEY (`UserId`) REFERENCES `AspNetUsers` (`Id`) ON DELETE CASCADE
      );
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (18ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE `AspNetUserLogins` (
          `LoginProvider` varchar(128) NOT NULL,
          `ProviderKey` varchar(128) NOT NULL,
          `ProviderDisplayName` longtext NULL,
          `UserId` varchar(95) NOT NULL,
          CONSTRAINT `PK_AspNetUserLogins` PRIMARY KEY (`LoginProvider`, `ProviderKey`),
          CONSTRAINT `FK_AspNetUserLogins_AspNetUsers_UserId` FOREIGN KEY (`UserId`) REFERENCES `AspNetUsers` (`Id`) ON DELETE CASCADE
      );
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (17ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE `AspNetUserRoles` (
          `UserId` varchar(95) NOT NULL,
          `RoleId` varchar(95) NOT NULL,
          CONSTRAINT `PK_AspNetUserRoles` PRIMARY KEY (`UserId`, `RoleId`),
          CONSTRAINT `FK_AspNetUserRoles_AspNetRoles_RoleId` FOREIGN KEY (`RoleId`) REFERENCES `AspNetRoles` (`Id`) ON DELETE CASCADE,
          CONSTRAINT `FK_AspNetUserRoles_AspNetUsers_UserId` FOREIGN KEY (`UserId`) REFERENCES `AspNetUsers` (`Id`) ON DELETE CASCADE
      );
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (15ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE TABLE `AspNetUserTokens` (
          `UserId` varchar(95) NOT NULL,
          `LoginProvider` varchar(128) NOT NULL,
          `Name` varchar(128) NOT NULL,
          `Value` longtext NULL,
          CONSTRAINT `PK_AspNetUserTokens` PRIMARY KEY (`UserId`, `LoginProvider`, `Name`),
          CONSTRAINT `FK_AspNetUserTokens_AspNetUsers_UserId` FOREIGN KEY (`UserId`) REFERENCES `AspNetUsers` (`Id`) ON DELETE CASCADE
      );
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (20ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE INDEX `IX_AspNetRoleClaims_RoleId` ON `AspNetRoleClaims` (`RoleId`);
fail: Microsoft.EntityFrameworkCore.Database.Command[20102]
      Failed executing DbCommand (8ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      CREATE UNIQUE INDEX `RoleNameIndex` ON `AspNetRoles` (`NormalizedName`);
MySql.Data.MySqlClient.MySqlException (0x80004005): Specified key was too long; max key length is 767 bytes ---> MySql.Data.MySqlClient.MySqlException (0x80004005): Specified key was too long; max key length is 767 bytes
   at MySqlConnector.Core.ResultSet.ReadResultSetHeaderAsync(IOBehavior ioBehavior) in C:\projects\mysqlconnector\src\MySqlConnector\Core\ResultSet.cs:line 42
   at MySql.Data.MySqlClient.MySqlDataReader.ActivateResultSet(ResultSet resultSet) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlDataReader.cs:line 80
   at MySql.Data.MySqlClient.MySqlDataReader.ReadFirstResultSetAsync(IOBehavior ioBehavior) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlDataReader.cs:line 302
   at MySql.Data.MySqlClient.MySqlDataReader.CreateAsync(MySqlCommand command, CommandBehavior behavior, ResultSetProtocol resultSetProtocol, IOBehavior ioBehavior) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlDataReader.cs:line 287
   at MySqlConnector.Core.TextCommandExecutor.ExecuteReaderAsync(String commandText, MySqlParameterCollection parameterCollection, CommandBehavior behavior, IOBehavior ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\Core\TextCommandExecutor.cs:line 37
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQueryAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlCommand.cs:line 261
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery() in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlCommand.cs:line 62
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
Failed executing DbCommand (8ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE UNIQUE INDEX `RoleNameIndex` ON `AspNetRoles` (`NormalizedName`);
MySql.Data.MySqlClient.MySqlException (0x80004005): Specified key was too long; max key length is 767 bytes ---> MySql.Data.MySqlClient.MySqlException (0x80004005): Specified key was too long; max key length is 767 bytes
   at MySqlConnector.Core.ResultSet.ReadResultSetHeaderAsync(IOBehavior ioBehavior) in C:\projects\mysqlconnector\src\MySqlConnector\Core\ResultSet.cs:line 42
   at MySql.Data.MySqlClient.MySqlDataReader.ActivateResultSet(ResultSet resultSet) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlDataReader.cs:line 80
   at MySql.Data.MySqlClient.MySqlDataReader.ReadFirstResultSetAsync(IOBehavior ioBehavior) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlDataReader.cs:line 302
   at MySql.Data.MySqlClient.MySqlDataReader.CreateAsync(MySqlCommand command, CommandBehavior behavior, ResultSetProtocol resultSetProtocol, IOBehavior ioBehavior) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlDataReader.cs:line 287
   at MySqlConnector.Core.TextCommandExecutor.ExecuteReaderAsync(String commandText, MySqlParameterCollection parameterCollection, CommandBehavior behavior, IOBehavior ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\Core\TextCommandExecutor.cs:line 37
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQueryAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlCommand.cs:line 261
   at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery() in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlCommand.cs:line 62
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_1.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Specified key was too long; max key length is 767 bytes
PM> 





Quale provider di MySql stai usando? Quelli prodotti da Oracle o quelli di Pomelo?
https://www.nuget.org/packages/Pomelo.EntityFrameworkCore.MySql


Sì utilizzo quello perchè era linkato nell'esempio sul sito ma anche il Provider di Oracle supporta Entity Framework giusto?

Telesoccorso Lineaperta: Servizi di Telesoccorso
11.382 messaggi dal 09 febbraio 2002
Contributi
Continua a usare il driver di Pomelo, è migliore di quello di Oracle.

Come vedi, hai un errore quando provi a eseguire le migration. Lo puoi risolvere in questo modo, indicando esplicitamente la lunghezza delle chiavi primarie.

https://stackoverflow.com/questions/48678495/net-core-2-0-with-mysql-specified-key-was-too-long-max-key-length-is-3072-byt

Se non ti dovesse funzionare, potresti eliminare le migration che hai ora (compreso il model snapshot), cambiare la connection string per farla puntare a un altro database vuoto e poi rifare una nuova migration dopo aver impostato la lunghezza delle chiavi.

Ovviamente elimina le migration solo se non ti importa di perdere quello che hai fatto finora.

ciao,
Moreno

Enjoy learning and just keep making

Torna al forum | Feed RSS

ASPItalia.com non è responsabile per il contenuto dei messaggi presenti su questo servizio, non avendo nessun controllo sui messaggi postati nei propri forum, che rappresentano l'espressione del pensiero degli autori.