Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

34 configurar formulário para salvar banco dados #35

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion CRM.ConsoleApp/CRM.ConsoleApp.sln
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Form", "teste\Form.csproj",
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DockerAspNet.API", "DockerAspNet.API\DockerAspNet.API\DockerAspNet.API.csproj", "{BB520F70-7F52-4112-8F82-014F4A7C4888}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApplication2", "WebApplication2\WebApplication2.csproj", "{9A87028B-CF05-4D00-84AE-AABB1A6EA632}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebApplication2", "WebApplication2\WebApplication2.csproj", "{9A87028B-CF05-4D00-84AE-AABB1A6EA632}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WebApplication3", "WebApplication3\WebApplication3.csproj", "{8C33F8DA-3341-4C7F-9435-0DA403CF002D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down Expand Up @@ -39,6 +41,10 @@ Global
{9A87028B-CF05-4D00-84AE-AABB1A6EA632}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9A87028B-CF05-4D00-84AE-AABB1A6EA632}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9A87028B-CF05-4D00-84AE-AABB1A6EA632}.Release|Any CPU.Build.0 = Release|Any CPU
{8C33F8DA-3341-4C7F-9435-0DA403CF002D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{8C33F8DA-3341-4C7F-9435-0DA403CF002D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8C33F8DA-3341-4C7F-9435-0DA403CF002D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8C33F8DA-3341-4C7F-9435-0DA403CF002D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
30 changes: 28 additions & 2 deletions CRM.ConsoleApp/WebApplication2/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,48 @@ namespace WebApplication2.Controllers
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly ApplicationDbContext _context;

public HomeController(ILogger<HomeController> logger)
public HomeController(ILogger<HomeController> logger, ApplicationDbContext context)
{
_logger = logger;
_context = context;
}

public IActionResult Index()
{
return View();
try
{
// Opera��es com o banco de dados
var usuarios = _context.Usuarios.ToList();
return View(usuarios);
}
catch (Exception ex)
{
_logger.LogError(ex, "Erro ao acessar a lista de usu�rios.");
return View("Error", new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}

public IActionResult Privacy()
{
return View();
}

public IActionResult AddUsuario()
{
var usuario = new Usuario
{
Nome = "Jo�o",
Sobrenome = "Silva",
CPF = "12345678900",
Telefone = "987654321"
};
_context.Usuarios.Add(usuario);
_context.SaveChanges();
return RedirectToAction("Index");
}

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
Expand Down
55 changes: 50 additions & 5 deletions CRM.ConsoleApp/WebApplication2/Controllers/UsuarioController.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebApplication2.Data;
using WebApplication2.Models;

namespace WebApplication2.Controllers
Expand Down Expand Up @@ -34,9 +33,46 @@ public async Task<IActionResult> Create([Bind("Nome,Sobrenome,CPF,Telefone")] Us
{
if (ModelState.IsValid)
{
_context.Add(usuario);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
try
{
_context.Add(usuario);
await _context.SaveChangesAsync();
Console.WriteLine("Usuário salvo com sucesso!"); // Log para debug
return RedirectToAction(nameof(Index));
}
catch (DbUpdateException dbEx)
{
Console.WriteLine("DbUpdateException: " + dbEx.Message);
if (dbEx.InnerException != null)
{
Console.WriteLine("InnerException: " + dbEx.InnerException.Message);
if (dbEx.InnerException.Message.Contains("could not connect"))
{
ModelState.AddModelError("", "Erro ao salvar os dados: Banco de dados não encontrado.");
}
else
{
ModelState.AddModelError("", "Erro ao salvar os dados: " + dbEx.InnerException.Message);
}
}
else
{
ModelState.AddModelError("", "Erro ao salvar os dados: " + dbEx.Message);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
ModelState.AddModelError("", "Erro ao salvar os dados: " + ex.Message);
}
}
else
{
Console.WriteLine("Erro no ModelState");
foreach (var error in ModelState.Values.SelectMany(v => v.Errors))
{
Console.WriteLine(error.ErrorMessage);
}
}
return View(usuario);
}
Expand Down Expand Up @@ -73,6 +109,7 @@ public async Task<IActionResult> Edit(int id, [Bind("Id,Nome,Sobrenome,CPF,Telef
{
_context.Update(usuario);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
catch (DbUpdateConcurrencyException)
{
Expand All @@ -85,7 +122,10 @@ public async Task<IActionResult> Edit(int id, [Bind("Id,Nome,Sobrenome,CPF,Telef
throw;
}
}
return RedirectToAction(nameof(Index));
catch (Exception ex)
{
ModelState.AddModelError("", "Erro ao atualizar os dados: " + ex.Message);
}
}
return View(usuario);
}
Expand Down Expand Up @@ -113,6 +153,11 @@ public async Task<IActionResult> Delete(int? id)
public async Task<IActionResult> DeleteConfirmed(int id)
{
var usuario = await _context.Usuarios.FindAsync(id);
if (usuario == null)
{
return NotFound();
}

_context.Usuarios.Remove(usuario);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
Expand Down
13 changes: 5 additions & 8 deletions CRM.ConsoleApp/WebApplication2/Data/ApplicationDbContext.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
using Microsoft.EntityFrameworkCore;
using WebApplication2.Models;

namespace WebApplication2.Data
public class ApplicationDbContext : DbContext
{
public class ApplicationDbContext : DbContext
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}

public DbSet<Usuario> Usuarios { get; set; } // Exemplo de uma entidade chamada Usuario
}

public DbSet<Usuario> Usuarios { get; set; }
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;

#nullable disable

namespace WebApplication2.Migrations
{
/// <inheritdoc />
public partial class CreateUsuarioTable : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Usuarios",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Nome = table.Column<string>(type: "text", nullable: false),
Sobrenome = table.Column<string>(type: "text", nullable: false),
CPF = table.Column<string>(type: "text", nullable: false),
Telefone = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Usuarios", x => x.Id);
});
}

/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Usuarios");
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace WebApplication2.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{

}

/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{

}
}
}
Loading