181 messaggi dal 10 agosto 2019
ciao a tutti ,volevo aggiungere delle tabelle ad un progetto del tipo asp .net core individual accounts

con tabella senza chiavi
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=aspnet-TestAddTable-C1639F27-DA45-45B6-9A72-3A00016E812A;Trusted_Connection=True;MultipleActiveResultSets=true;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables Message -force
uso poi la classe in models da un controller e tutto và come mi aspettavo


con tabella con chiave
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=aspnet-TestAddTable-C1639F27-DA45-45B6-9A72-3A00016E812A;Trusted_Connection=True;MultipleActiveResultSets=true;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables MessageWithKey

ho aggiunto la chiave tra il campo Id di AspNetUsers ed il campo IdUtente della tabella MessageWithKey

eseguendo ottengo i messaggi:

For foreign key FK_MessageWithKey_AspNetUsers1 on table dbo.MessageWithKey, unable to model the end of the foreign key on principal table dbo.AspNetUsers. This is usually because the principal table was not included in the selection set.
The following file(s) already exist in directory C:\Users\gianmarco\Source\Repos\TestAddTable\Models: aspnetTestAddTableC1639F27DA4545B69A723A00016E812AContext.cs. Use the Force flag to overwrite these files.

eseguendo il seguente comando non ritornano errori:
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=aspnet-TestAddTable-C1639F27-DA45-45B6-9A72-3A00016E812A;Trusted_Connection=True;MultipleActiveResultSets=true;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables MessageWithKey,AspNetUsers -force

però ricevo un errore se provo ad usare la classe MessageWithKey sotto Model facendo un controller :
"Si è verificato un errore durante l'esecuzione del generatore di codice selezionato.
'Cannot use table AspNetUsers for entity type 'IdentityUser' and there is no relationship between their primary keys'

spero in un vostro suggerimento ,grazie
11.886 messaggi dal 09 febbraio 2002
Contributi
Ciao e benvenuto nel forum!
Puoi far vedere come ti è stata creata la classe MessageWithKey?
La sua relazione con AspNetUsers è stata mappata nel DbContext? Fai vedere anche il codice che si trova nel suo metodo OnModelCreating.

Intanto ti mando un articolo che mostra come mappare un'entità relazionata all'utente.
https://www.aspitalia.com/articoli/asp.net-core/personalizzare--aspnet-core-identity-p-3.aspx#title_2
Vedi il paragrafo "Aggiungere un'entità correlata all'utente".

ciao,
Moreno

Enjoy learning and just keep making
181 messaggi dal 10 agosto 2019
ho fatto un nuovo progetto perchè l'altro era un pò pasticciato,
ho aggiunto la tabella MessageWithKey

ho eseguito il comando: Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=aspnet-TestWithKey-0E6FB1F9-BD7A-4E90-AC2C-CC66E592F25C;Trusted_Connection=True;MultipleActiveResultSets=true;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables MessageWithKey,AspNetUsers

e non ho ricevuto nessun errore
segue la classe MessageWithKey

using System;
using System.Collections.Generic;

namespace TestWithKey.Models
{
public partial class MessageWithKey
{
public int Id { get; set; }
public string IdUtente { get; set; }
public string Testo { get; set; }

public virtual AspNetUsers IdUtenteNavigation { get; set; }
}
}


l'uso di database first ha comportato la creazione di un nuovo dbcontext

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace TestWithKey.Models
{
public partial class aspnetTestWithKey0E6FB1F9BD7A4E90AC2CCC66E592F25CContext : DbContext
{
public aspnetTestWithKey0E6FB1F9BD7A4E90AC2CCC66E592F25CContext()
{
}

public aspnetTestWithKey0E6FB1F9BD7A4E90AC2CCC66E592F25CContext(DbContextOptions<aspnetTestWithKey0E6FB1F9BD7A4E90AC2CCC66E592F25CContext> options)
: base(options)
{
}

public virtual DbSet<AspNetUsers> AspNetUsers { get; set; }
public virtual DbSet<MessageWithKey> MessageWithKey { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=aspnet-TestWithKey-0E6FB1F9-BD7A-4E90-AC2C-CC66E592F25C;Trusted_Connection=True;MultipleActiveResultSets=true;");
}
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "2.2.4-servicing-10062");

modelBuilder.Entity<AspNetUsers>(entity =>
{
entity.HasIndex(e => e.NormalizedEmail)
.HasName("EmailIndex");

entity.HasIndex(e => e.NormalizedUserName)
.HasName("UserNameIndex")
.IsUnique()
.HasFilter("([NormalizedUserName] IS NOT NULL)");

entity.Property(e => e.Id).ValueGeneratedNever();

entity.Property(e => e.Email).HasMaxLength(256);

entity.Property(e => e.NormalizedEmail).HasMaxLength(256);

entity.Property(e => e.NormalizedUserName).HasMaxLength(256);

entity.Property(e => e.UserName).HasMaxLength(256);
});

modelBuilder.Entity<MessageWithKey>(entity =>
{
entity.Property(e => e.IdUtente)
.HasColumnName("Id_Utente")
.HasMaxLength(450);

entity.Property(e => e.Testo).HasColumnName("testo");

entity.HasOne(d => d.IdUtenteNavigation)
.WithMany(p => p.MessageWithKey)
.HasForeignKey(d => d.IdUtente)
.HasConstraintName("FK_MessageWithKey_AspNetUsers");
});
}
}
}

l'uso di dadatabase first ha comportato anche la creazione di una classe AspNetUsers sotto Models

using System;
using System.Collections.Generic;

namespace TestWithKey.Models
{
public partial class AspNetUsers
{
public AspNetUsers()
{
MessageWithKey = new HashSet<MessageWithKey>();
}

public string Id { get; set; }
public string UserName { get; set; }
public string NormalizedUserName { get; set; }
public string Email { get; set; }
public string NormalizedEmail { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }devo
public string ConcurrencyStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public DateTimeOffset? LockoutEnd { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }

public virtual ICollection<MessageWithKey> MessageWithKey { get; set; }
}
}

ho provato ad aggiungere un controller usando la classe MessageWithKeys ed il db context aspnetTestWithKey0E6FB1F9BD7A4E90AC2CCC66E592F25CContext ma quando chiamo il controller ottengo il seguente messaggio di errore:

An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'TestWithKey.Models.aspnetTestWithKey0E6FB1F9BD7A4E90AC2CCC66E592F25CContext' while attempting to activate 'TestWithKey.Controllers.MessageWithKeysController'.

se provo a creare un controller usando ApplicationDbCOntext ottengo l'errore :

"Si è verificato un errore durante l'esecuzione del generatore di codice selezionato.
'Cannot use table AspNetUsers for entity type 'IdentityUser' and there is no relationship between their primary keys'

se devo fornire altre informazioni dimmi pure cercherò d'essere più chiaro,grazie per l'aiuto,ciao
181 messaggi dal 10 agosto 2019
credo che un errore fosse non valorizzare la classe StartUp non aggiungendo :

var connection = @"Server=(localdb)\mssqllocaldb;Database=Blogging2;Trusted_Connection=True;";

services.AddDbContext<Blogging2Context>(options => options.UseSqlServer(connection));

pensavo che il database first inizializzasse tutto da solo,sorry
11.886 messaggi dal 09 febbraio 2002
Contributi
Ciao, quindi ora sei riuscito a risolvere il problema?

Enjoy learning and just keep making
181 messaggi dal 10 agosto 2019
ciao, ho aggiunto un dbcontext in startup avendone quindi due:

services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDbContext<aspnetTestIndividualAccounts057B884DBE48457AB06B1FBB3B480A9FContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));

sembra funzionare ma non sò quanto sia una soluzione accettabile,spero in un tuo consiglio,grazie,ciao
Modificato da surfernet123 il 13 agosto 2019 20:23 -
11.886 messaggi dal 09 febbraio 2002
Contributi
Ciao,

sembra funzionare ma non sò quanto sia una soluzione accettabile


Ok, effettivamente è meglio averne uno solo, a meno che tu non abbia esigenze particolari.
Fai così, procedi poco alla volta. Per prima cosa apri l'ApplicationDbContext che sarà l'unico DbContext che andrai a usare. Al suo interno aggiungi questo metodo (ammesso che non esista già).
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  base.OnModelCreating(modelBuilder);
}



Adesso apri il DbContext aspnetTestIndividual... e dentro ci troverai delle proprietà di tipo DbSet<T>. Scegline una, magari una che non ha relazioni con altre entità. Copiala e incollala nel contesto ApplicationDbContext.

Torna in aspnetTestIndividual... e vai nel suo metodo OnModelCreating. Copiati il codice di mapping che riguarda l'entità del DbSet<T> che avevi scelto. Incollalo nell'ApplicationDbContext, all'interno del SUO metodo OnModelCreating, subito sotto base.OnModelCreating(modelBuilder);. Esegui l'applicazione e prova ad usare l'ApplicationDbContext e a fare una query LINQ rivolta al DbSet<T> che avevi scelto. Se tutto funziona, ripeti finché non hai copiato tutti i DbSet<T> e tutto il codice di mapping.

A quel punto potrai eliminare il DbContext aspnetTestIndividual...

ciao,
Moreno
Modificato da BrightSoul il 14 agosto 2019 23:07 -

Enjoy learning and just keep making
181 messaggi dal 10 agosto 2019
grazie per la risposta e grazie mille per la spiegazione,ciao

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.