Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 13
  1. #1

    Update dati con entity framework

    ciao!

    faccio tre premesse:
    • il progetto non è mio, ma me lo sono ritrovato ed è un vero casino
    • non sono espertissimo di .net ed EF
    • sono due ore che cerco una soluzione/linea guida, ma non riesco a fare il match tra quello che trovo e sto progetto


    detto ciò, in un controller ho questo metodo:
    codice:
            [HttpPost("changepwd")]
            [AllowAnonymous]
            public async Task<IActionResult> ChangePwd([FromBody] ChangePasswordRequest changePwdRequest)
            {
                Utente user;
                ChangePasswordResponse response = new ChangePasswordResponse();
                try
                {
                    user = await _userManager.FindByNameAsync(changePwdRequest.Email);
                    if (user == null)
                        throw new Exception("Utente non trovato.");
    
    
                    var result = await _userManager.ResetPasswordAsync(user, changePwdRequest.Code, changePwdRequest.ConfirmPassword);
                    response.IsSuccess = result.Succeeded;
                    response.Errors = result.Errors.Select(x => x.Description);
    
    
                    // UPDATE DEI CAMPI UTENTE
    
    
                    return Ok(response);
                }
                catch (Exception ex)
                {
                    _logger.LogInformation($"Email confirmation error: {ex.Message} - UserID: {changePwdRequest.Email} - Code: {changePwdRequest.Code}");
                    response.Errors = new List<string> { ex.Message };
                    response.IsSuccess = false;
                    return Ok(response);
                }
            }
    la dove ho lasciato il commento dovrei fare l'update di due campi della tabella degli utenti.
    usando EF.
    avete qualche suggerimento da darmi??

  2. #2
    per ora ho risolto banalmente con il classico SqlConnection/ecc.
    tanto si tratta di fare un update qui e di una query da un'altra parte.

  3. #3
    Moderatore di Programmazione L'avatar di alka
    Registrato dal
    Oct 2001
    residenza
    Reggio Emilia
    Messaggi
    24,461
    Quote Originariamente inviata da fermat Visualizza il messaggio
    la dove ho lasciato il commento dovrei fare l'update di due campi della tabella degli utenti.
    usando EF.
    avete qualche suggerimento da darmi??
    Non è chiaro quale sia il tuo dubbio.

    Non sai come aggiornare dati con Entity Framework?
    Oppure non sai come aggiornare le informazioni specifiche dell'utente?

    Spiega meglio, nel caso.
    MARCO BREVEGLIERI
    Software and Web Developer, Teacher and Consultant

    Home | Blog | Delphi Podcast | Twitch | Altro...

  4. #4
    Moderatore di Programmazione L'avatar di alka
    Registrato dal
    Oct 2001
    residenza
    Reggio Emilia
    Messaggi
    24,461
    Quote Originariamente inviata da fermat Visualizza il messaggio
    la dove ho lasciato il commento dovrei fare l'update di due campi della tabella degli utenti.
    usando EF.
    avete qualche suggerimento da darmi??
    Non è chiaro quale sia il tuo dubbio.

    Non sai come aggiornare dati con Entity Framework?
    Oppure non sai come aggiornare le informazioni specifiche dell'utente?

    Spiega meglio, nel caso.
    MARCO BREVEGLIERI
    Software and Web Developer, Teacher and Consultant

    Home | Blog | Delphi Podcast | Twitch | Altro...

  5. #5
    ciao alka.

    allora, il discorso è che faccio fatica ad adattare i miei ricordi su EF e la documentazione che trovo su sto progetto.

    cmq, questo è l'ultimo test che ho fatto:
    codice:
    [HttpPost("changepwd")]
    [AllowAnonymous]
    public async Task<IActionResult> ChangePwd([FromBody] ChangePasswordRequest changePwdRequest)
    {
    	Utente user;
    	ChangePasswordResponse response = new ChangePasswordResponse();
    	try
    	{
    		user = await _userManager.FindByNameAsync(changePwdRequest.Email);
    		if (user == null)
    			throw new Exception("Utente non trovato.");
    
    
    		var result = await _userManager.ResetPasswordAsync(user, changePwdRequest.Code, changePwdRequest.ConfirmPassword);
    		response.IsSuccess = result.Succeeded;
    		response.Errors = result.Errors.Select(x => x.Description);
    
    
    		// UPDATE DEI CAMPI UTENTE
    		var newUser = new Utente();
    		//newUser.Email = changePwdRequest.Email;
    		newUser.HasChanged = true;
    		using (var dbContext = new ClonidentDbContext())
    		{
    			dbContext.Users.Attach(newUser);
    			dbContext.Entry(user).Property(x => x.HasChanged).IsModified = true;
    			dbContext.SaveChanges();
    		}
    
    
    		return Ok(response);
    	}
    	catch (Exception ex)
    	{
    		_logger.LogInformation($"Email confirmation error: {ex.Message} - UserID: {changePwdRequest.Email} - Code: {changePwdRequest.Code}");
    		response.Errors = new List<string> { ex.Message };
    		response.IsSuccess = false;
    		return Ok(response);
    	}
    }
    l'errore che ottengo è questo:
    codice:
    • No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
    dentro Startup.cs ho trovato questo:
    codice:
    string connectionString = Configuration["ConnectionString:ClonidentDbSvil"];
    services.AddDbContext<ClonidentDbContext>(options => 
             options.UseSqlServer(connectionString).EnableSensitiveDataLogging());
    dove ClonidentDbContext è questo (non te lo riporto tutto perchè troppo lungo):
    codice:
    // <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
    using System;
    using BCSoft.Clonident.DatabaseContext.EF.Entities;
    using BCSoft.Clonident.DatabaseContext.EF.Entities.Cross;
    using BCSoft.Clonident.DatabaseContext.EF.Entities.Tipologiche;
    using BCSoft.Clonident.DatabaseContext.EF.Entities.Statistiche;
    using Microsoft.AspNetCore.Identity;
    using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
    using Microsoft.Data.SqlClient;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Metadata;
    
    
    #nullable disable
    
    
    namespace BCSoft.Clonident.DatabaseContext.EF
    {
        public partial class ClonidentDbContext : IdentityDbContext<Utente, Ruolo, string, IdentityUserClaim<string>, RuoloUtente, IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>>
        {
            public ClonidentDbContext()
            {
            }
    
    
            public ClonidentDbContext(DbContextOptions<ClonidentDbContext> options)
                : base(options)
            {
            }
    
    
    		// .....................
    
    
    
    		
            public DbSet<Utente> Utentes { get; set; } // AGGIUNTO DA ME
    
    
            private static void ConfigureCustomIdentityRules(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Utente>(b =>
                {
    
    
                    // Each User can have many entries in the UserRole join table
                    b.HasMany(e => e.UserRoles)
                        .WithOne(e => e.User)
                        .HasForeignKey(ur => ur.UserId)
                        .IsRequired();
                });
    
    
                modelBuilder.Entity<Ruolo>(b =>
                {
                    // Each Role can have many entries in the UserRole join table
                    b.HasMany(e => e.UserRoles)
                        .WithOne(e => e.Role)
                        .HasForeignKey(ur => ur.RoleId)
                        .IsRequired();
                });
                modelBuilder.Entity<RuoloUtente>(e =>
                    {
                        e.HasOne(x => x.Role).WithMany(x => x.UserRoles).HasForeignKey(s => s.RoleId).IsRequired();
                        e.HasOne(x => x.User).WithMany(x => x.UserRoles).HasForeignKey(s => s.UserId).IsRequired();
                    }
                );
            }
    
    
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.HasAnnotation("Relational:Collation", "Latin1_General_CI_AS");
    
    
    			// ........................
    			
                OnModelCreatingPartial(modelBuilder);
                base.OnModelCreating(modelBuilder);
                ConfigureCustomIdentityRules(modelBuilder);
            }
    
    
            partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
            public int NextValueForSequence()
            {
                SqlParameter result = new SqlParameter("@result", System.Data.SqlDbType.Int)
                {
                    Direction = System.Data.ParameterDirection.Output
                };
                Database.ExecuteSqlRaw($"SELECT @result = (NEXT VALUE FOR PraticaNumbers)", result);
                return (int)result.Value;
            }
        }
    }
    ho fatto un pò di ricerche in giro, ma non capisco come risolvere.
    perchè su un altro progetto, sicuramente più "lineare" di questo, non avevo tutti sti problemi.
    quindi non capisco se sono io che non ci sto capendo nulla, o è il progetto complicato.

  6. #6
    Moderatore di Programmazione L'avatar di alka
    Registrato dal
    Oct 2001
    residenza
    Reggio Emilia
    Messaggi
    24,461
    Quote Originariamente inviata da fermat Visualizza il messaggio
    l'errore che ottengo è questo: [...]
    E' fondamentale capire qual è la riga che ti genera questo errore, perché a quella base dati accedono probabilmente - tramite DbContext - sia la parte di Identity che le classi preposte all'accesso ai dati per la loro manipolazione.

    Una di queste parti non è configurata a dovere.

    Esegui il debug passo per passo o abilita lo stop sulle eccezioni per capire su quale riga si verifica l'errore e poi controlla lo stack delle chiamate nei dettagli della stessa eccezione: da queste evidenze, dovresti capire qual è la parte configurata che genera l'errore.
    MARCO BREVEGLIERI
    Software and Web Developer, Teacher and Consultant

    Home | Blog | Delphi Podcast | Twitch | Altro...

  7. #7
    allora, ho messo vari punti di interruzione.

    questo il pezzo di codice, ho messo dei commenti:
    codice:
                    var newUser = new Utente();
                    newUser.HasChanged = true;
                    using (var dbContext = new ClonidentDbContext())
                    {
                        dbContext.Users.Attach(newUser); // PUNTO DI INTERRUZIONE, NON DA ANCORA ERRORE
                        dbContext.Entry(user).Property(x => x.HasChanged).IsModified = true; // PUNTO DI INTERRUZIONE, DA ERRORE
                        //dbContext.SaveChanges();
                    }

  8. #8
    Utente di HTML.it L'avatar di U235
    Registrato dal
    Mar 2006
    Messaggi
    1,536
    Quote Originariamente inviata da fermat Visualizza il messaggio
    allora, ho messo vari punti di interruzione.

    questo il pezzo di codice, ho messo dei commenti:
    codice:
                    var newUser = new Utente();
                    newUser.HasChanged = true;
                    using (var dbContext = new ClonidentDbContext())
                    {
                        dbContext.Users.Attach(newUser); // PUNTO DI INTERRUZIONE, NON DA ANCORA ERRORE
                        dbContext.Entry(user).Property(x => x.HasChanged).IsModified = true; // PUNTO DI INTERRUZIONE, DA ERRORE
                        //dbContext.SaveChanges();
                    }
    Perché crei un nuovo oggetto ClonidentDbContext e non usi quello che dovresti poter recuperare dal costruttore del controller?
    Ultima modifica di U235; 19-12-2023 a 04:10

  9. #9
    Moderatore di Programmazione L'avatar di alka
    Registrato dal
    Oct 2001
    residenza
    Reggio Emilia
    Messaggi
    24,461
    Quote Originariamente inviata da fermat Visualizza il messaggio
    codice:
    dbContext.Entry(user).Property(x => x.HasChanged).IsModified = true; // PUNTO DI INTERRUZIONE, DA ERRORE
    Perché usi il metodo Entry e non carichi l'entità dal Context?
    Siamo sicuri che quell'user possa essere effettivamente "agganciato" al contesto (ovvero che corrisponda a qualcosa di tangibile su DB)?

    Non credo sia poi quell'istruzione a darti l'errore che hai segnalato... o sì?
    MARCO BREVEGLIERI
    Software and Web Developer, Teacher and Consultant

    Home | Blog | Delphi Podcast | Twitch | Altro...

  10. #10
    Moderatore di Programmazione L'avatar di alka
    Registrato dal
    Oct 2001
    residenza
    Reggio Emilia
    Messaggi
    24,461
    Quote Originariamente inviata da fermat Visualizza il messaggio
    codice:
    dbContext.Entry(user).Property(x => x.HasChanged).IsModified = true; // PUNTO DI INTERRUZIONE, DA ERRORE
    Perché usi il metodo Entry e non carichi l'entità dal Context?
    Siamo sicuri che quell'user possa essere effettivamente "agganciato" al contesto (ovvero che corrisponda a qualcosa di tangibile su DB)?

    Non credo sia poi quell'istruzione a darti l'errore che hai segnalato... o sì?
    MARCO BREVEGLIERI
    Software and Web Developer, Teacher and Consultant

    Home | Blog | Delphi Podcast | Twitch | Altro...

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.