Download .NET

Para fazer o download do .NET Core acesse www.microsoft.com/net, feito isso na tela inicial aparecerá um link para download, clique sobre ele e abrirá uma nova janela.

Faça download da última versão disponível e faça a instalação logo após.

Nessa mesma página você também pode baixar todas versões disponível do .NET Framework Full, também IDE do Visual Studio e Visual Code, essa página foi a melhor coisa que pode acontecer, tudo que eu preciso está aqui, tornando mais fácil a vida de quem precisa fazer um download.

IDE de desenvolvimento

Neste artigo estou utilizando o Visual Studio Community 2017 15.5.1, mais você pode utilizar uma mais atualizada ou Visual Code, que é uma IDE Open source e super leve, se você querer utilizar o Visual Code acessi aqui: https://code.visualstudio.com/?wt.mc_id=DX_841432

Criando um projeto

Estarei mostrando a você como criar uma pequena aplicação usando Asp.NET Core + SQLite, não estarei me aprofundando em muitos detalhes, nosso objetivo aqui é apenas mostrar como criar um aplicação passo-a-passo, para aqueles que estão iniciando.

Existem vários artigos na internet sobre como criar uma aplicação, mais muitos iniciantes, que estão chegando ao mundo .NET Core, ainda tem dificuldades, então isso me motivou a fazer um PASSO-A-PASSO de uma aplicação simples do ZERO.

This is a simple application, but with it you will learn how to Add, Update, Delete and List a Customer ( Basic ) record.

All of our step-by-step will be illustrated by images from the IDE for easy reading, let's create our project.

Notes : This is a project intended for people who are learning Asp.Net Core.

Open your Visual Studio and let's start ...

After clicking OK we will have the following structure in our project.

Let's create our classes , follow the steps below.

Class Code - CrudBasicoNETCoreMVC.Models

using System.ComponentModel.DataAnnotations;
namespace CrudBasicoNETCoreMVC.Models
{
 public class Situacoes
 {
 [Key]
 public int Id { get; set; }
 
 public string Descricao { get; set; }
 
 public bool Ativo { get; set; }
 }
}

Class Code - CrudBasicoNETCoreMVC.Models

using System.ComponentModel.DataAnnotations;
namespace CrudBasicoNETCoreMVC.Models
{
 public class Clientes
 {
 [Key]
 public int Id { get; set; }
 
 [StringLength(100)]
 public string Nome { get; set; }
 
 [StringLength(100)]
 public string Apelido { get; set; }
 
 [StringLength(100)]
 public string Endereco { get; set; }
 
 [StringLength(100)]
 public string Bairro { get; set; }
 
 [StringLength(2)]
 public string Estado { get; set; }
 
 [StringLength(100)]
 public string Cidade { get; set; }
 
 public string Observacoes { get; set; }
 
 public int SituacaoId { get; set; }
 
 public Situacoes Situacao { get; set; }
 }
}

Let's create our class responsible for accessing the database .

Database Class Code

 

using Microsoft.EntityFrameworkCore;
namespace CrudBasicoNETCoreMVC.Models
{
 public class CrudDbContext : DbContext
 {
 public DbSet<Clientes> Clientes { get; set; }
 public DbSet<Situacoes> Situacoes { get; set; }
 
 public CrudDbContext(DbContextOptions<CrudDbContext> options)
 { }
 
 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 {
 if (!optionsBuilder.IsConfigured)
 {
 optionsBuilder.UseSqlite("DataSource=crudnetcoremvc.db");
 }
 base.OnConfiguring(optionsBuilder);
 }
 
 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
 modelBuilder
 .Entity<Clientes>()
 .HasOne(p => p.Situacao);
 
 base.OnModelCreating(modelBuilder);
 }
 }
}

Let's now create the Customers and Situations folders for our Views .

Now let's create our View Code.

View Code

   

 

 

@model CrudBasicoNETCoreMVC.Models.Clientes
@{
 var estados = CrudBasicoNETCoreMVC.Util.Estados;
}
<p class="card">
 <p class="header">
 <h4 class="title">Editar Cadastro</h4>
 </p>
 <p class="content">
 <form asp-action="Gravar" role="form">
 <p class="row">
 <p class="col-md-2">
 <p class="form-group">
 <label>Código</label>
 <input asp-for="@Model.Id" type="text" class="form-control border-input disabled" readonly value="@Model.Id">
 </p>
 </p>
 <p class="col-md-5">
 <p class="form-group">
 <label>Nome do Cliente</label>
 <input asp-for="@Model.Nome" type="text" class="form-control border-input" placeholder="Nome" value="@Model.Nome">
 </p>
 </p>
 <p class="col-md-5">
 <p class="form-group">
 <label for="exampleInputEmail1">Apelido</label>
 <input asp-for="@Model.Apelido" type="text" class="form-control border-input" placeholder="Apelido" value="@Model.Apelido">
 </p>
 </p>
 </p>
 <p class="row">
 <p class="col-md-6">
 <p class="form-group">
 <label>Endereço</label>
 <input asp-for="@Model.Endereco" type="text" class="form-control border-input" placeholder="Endereço" value="@Model.Endereco">
 </p>
 </p>
 <p class="col-md-6">
 <p class="form-group">
 <label>Bairro</label>
 <input asp-for="@Model.Bairro" type="text" class="form-control border-input" placeholder="Bairro" value="@Model.Bairro">
 </p>
 </p>
 </p>
 <p class="row">
 <p class="col-md-6">
 <p class="form-group">
 <label>Cidade</label>
 <input asp-for="@Model.Cidade" type="text" class="form-control border-input" placeholder="Cidade" value="@Model.Cidade">
 </p>
 </p>
 <p class="col-md-2">
 <p class="form-group">
 <label>Estado</label>
 <select asp-for="@Model.Estado" asp-items="@estados" class="form-control border-input"></select>
 </p>
 </p>
 <p class="col-md-4">
 <p class="form-group">
 <label>Situação</label>
 <select asp-for="@Model.SituacaoId" asp-items="@ViewBag.Situacoes" class="form-control border-input"></select>
 </p>
 </p>
 </p>
 <p class="row">
 <p class="col-md-12">
 <p class="form-group">
 <label>Obervações</label>
 <textarea asp-for="@Model.Observacoes" rows="5" class="form-control border-input" placeholder="">@Model.Observacoes</textarea>
 </p>
 </p>
 </p>
 <p class="text-center">
 <button type="submit" class="btn btn-danger btn-fill btn-wd">Gravar</button>
 <a class="btn btn-danger btn-icon  btn-fill btn-wd" asp-controller="clientes" asp-action="index"><i class="fa fa-undo"></i></a>
 </p>
 <p class="clearfix"></p>
 </form>
 </p>
</p>

View code - Index.cshtml

Once this is done, create another View named Index.cshtml by following the previous step.

@using CrudBasicoNETCoreMVC.Models
@model List<Clientes>
 
<p class="row">
 <p class="col-md-12">
 <p class="card">
 <p class="header">
 <h4 class="title">Clientes</h4>
 <p class="category">
 Exibe lista dos clientes cadastrados
 <a class="btn btn-sm btn-success btn-icon" asp-controller="clientes" asp-action="editar" asp-route-id="0">Novo</a>
 </p>
 </p>
 <p class="content table-responsive table-full-width">
 <table class="table table-striped">
 <thead class="text-primary" style="background-color: beige">
 <tr>
 <th>Ação</th>
 <th>Nome</th>
 <th>Endereço</th>
 <th>Cidade</th>
 <th>Estado</th>
 <th>Situação</th>
 </tr>
 </thead>
 <tbody>
 @foreach (var item in Model)
 {
 <tr>
 <td>
 <a class="btn btn-sm btn-danger btn-icon" asp-controller="clientes" asp-action="editar" asp-route-id="@item.Id"><i class="fa fa-pencil-square-o"></i></a>
 <a class="btn btn-sm btn-danger btn-icon" asp-controller="clientes" asp-action="excluir" asp-route-id="@item.Id"><i class="fa fa-trash-o"></i></a>
 </td>
 <td>@item.Nome</td>
 <td>@item.Endereco</td>
 <td>@item.Cidade</td>
 <td>@item.Estado</td>
 <td>@item.Situacao.Descricao</td>
 </tr>
 }
 </tbody>
 </table>
 </p>
 </p>
 </p>
</p>

After you create the View Index.cshtml, repeat the same steps for the Situations folder.

View - Edit.cshtml - Situations

@model CrudBasicoNETCoreMVC.Models.Situacoes
<p class="card">
 <p class="header">
 <h4 class="title">Editar Situação</h4>
 </p>
 <p class="content">
 <form asp-action="Gravar" role="form">
 <p class="row">
 <p class="col-md-2">
 <p class="form-group">
 <label>Código</label>
 <input asp-for="@Model.Id" type="text" class="form-control border-input disabled" readonly value="@Model.Id">
 </p>
 </p>
 <p class="col-md-5">
 <p class="form-group">
 <label>Descrição da Situação</label>
 <input asp-for="@Model.Descricao" type="text" class="form-control border-input" placeholder="Descrição" value="@Model.Descricao">
 </p>
 </p>
 <p class="col-md-5">
 <p class="form-group">
 <label for="exampleInputEmail1">Status</label>
 <input asp-for="@Model.Ativo" type="checkbox" class="form-control border-input" value="@Model.Ativo">
 </p>
 </p>
 </p>
 <p class="text-center">
 <button type="submit" class="btn btn-danger btn-fill btn-wd">Gravar</button>
 <a class="btn btn-danger btn-icon  btn-fill btn-wd" asp-controller="situacoes" asp-action="index"><i class="fa fa-undo"></i></a>
 </p>
 <p class="clearfix"></p>
 </form>
 </p>
</p>

View - Index.cshtml - Situations

@using CrudBasicoNETCoreMVC.Models
@model List<Situacoes>
 
<p class="row">
 <p class="col-md-12">
 <p class="card">
 <p class="header">
 <h4 class="title">Clientes</h4>
 <p class="category">
 Exibe situações cadastradas
 <a class="btn btn-sm btn-danger btn-icon" asp-controller="situacoes" asp-action="editar" asp-route-id="0"><i class="fa fa-plus"></i></a>
 </p>
 </p>
 <p class="content table-responsive table-full-width">
 <table class="table table-striped">
 <thead class="text-primary" style="background-color: beige">
 <tr>
 <th>Ação</th>
 <th>Descrição</th>
 <th>Ativo</th>
 </tr>
 </thead>
 <tbody>
 @foreach (var item in Model)
 {
 <tr>
 <td>
 <a class="btn btn-sm btn-danger btn-icon" asp-controller="situacoes" asp-action="editar" asp-route-id="@item.Id"><i class="fa fa-pencil-square-o"></i></a>
 <a class="btn btn-sm btn-danger btn-icon" asp-controller="situacoes" asp-action="excluir" asp-route-id="@item.Id"><i class="fa fa-trash-o"></i></a>
 </td>
 <td>@item.Descricao</td>
 <td>@item.Ativo</td>
 </tr>
 }
 </tbody>
 </table>
 </p>
 </p>
 </p>
</p>

Let's now create our Controller 

Code class controller situations:

using CrudBasicoNETCoreMVC.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq;
 
namespace CrudBasicoNETCoreMVC.Controllers
{
 public class SituacoesController : Controller
 {
 private CrudDbContext _crudContext;
 
 public SituacoesController(CrudDbContext crudContext)
 {
 _crudContext = crudContext;
 }
 
 public IActionResult Index()
 {
 var situacoes = _crudContext.Situacoes.AsNoTracking().ToList();
 return View(situacoes);
 }
 
 public IActionResult Excluir(int id)
 {
 var situacao = _crudContext.Situacoes.Single(p => p.Id == id);
 _crudContext.Remove(situacao);
 _crudContext.SaveChanges();
 
 return RedirectToAction("Index");
 }
 
 public IActionResult Editar(int id)
 {
 var situacao = _crudContext.Situacoes.FirstOrDefault(p => p.Id == id) ?? new Situacoes();
 
 return View(situacao);
 }
 
 public IActionResult Gravar(Situacoes situacao)
 {
 
 if (situacao.Id > 0)
 {
 _crudContext.Update(situacao);
 }
 else
 {
 _crudContext.Add(situacao);
 }
 
 _crudContext.SaveChanges();
 
 return RedirectToAction("Editar", new { id = situacao.Id });
 }
 }
}

Follow the previous step to create the Controller clients as well.

Client controller class code

using CrudBasicoNETCoreMVC.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using System.Linq;
  
namespace CrudBasicoNETCoreMVC.Controllers
{
 public class ClientesController : Controller
 
 {
 private CrudDbContext _crudContext;
 public ClientesController(CrudDbContext crudContext)
 {
 _crudContext = crudContext;
 }
  
 public IActionResult Index()
 {
 var clientes = _crudContext
 .Clientes
 .Include(i => i.Situacao)
 .AsNoTracking()
 .ToList();
  
 return View(clientes);
 }
  
 public IActionResult Excluir(int id)
 {
 var cliente = _crudContext.Clientes.Single(p => p.Id == id);
 _crudContext.Remove(cliente);
 _crudContext.SaveChanges();
 return RedirectToAction("Index");
 }
  
 public IActionResult Editar(int id)
 {
 ViewBag.Situacoes = _crudContext
 .Situacoes
 .Select(c => new SelectListItem() { Text = c.Descricao, Value = c.Id.ToString() })
 .ToList();
  
 var cliente = _crudContext.Clientes.FirstOrDefault(p => p.Id == id) ?? new Clientes();
  
 return View(cliente);
}
  
 public IActionResult Gravar(Clientes cliente)
 {
  
 if (cliente.Id > 0)
 {
 _crudContext.Update(cliente);
 }
 else
 {
 _crudContext.Add(cliente);
 }
  
 _crudContext.SaveChanges();
  
 return RedirectToAction("Editar", new { id = cliente.Id });
 }
 }
}

This will create a class called " Util " to insert the list of states in it. Code of the class Util.cs: Notes: in another article I will show details about the SelectListItem

 

 

using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
  
namespace CrudBasicoNETCoreMVC
{
 public class Util
 {
 public static List<SelectListItem> Estados = new List<SelectListItem>
 {
 new SelectListItem { Value="AC", Text = "Acre"},
 new SelectListItem { Value="AL", Text = "Alagoas"},
 new SelectListItem { Value="AP", Text = "Amapá"},
 new SelectListItem { Value="AM", Text = "Amazonas"},
 new SelectListItem { Value="BA", Text = "Bahia"},
 new SelectListItem { Value="CE", Text = "Ceará"},
 new SelectListItem { Value="DF", Text = "Distrito Federal"},
 new SelectListItem { Value="ES", Text = "Espírito Santo"},
 new SelectListItem { Value="GO", Text = "Goiás"},
 new SelectListItem { Value="MA", Text = "Maranhão"},
 new SelectListItem { Value="MT", Text = "Mato Grosso"},
 new SelectListItem { Value="MS", Text = "Mato Grosso do Sul"},
 new SelectListItem { Value="MG", Text = "Minas Gerais"},
new SelectListItem { Value="PA", Text = "Pará"},
 new SelectListItem { Value="PB", Text = "Paraíba"},
 
ew SelectListItem { Value="PR", Text = "Paraná"},
 new SelectListItem { Value="PE", Text = "Pernambuco"},
 new SelectListItem { Value="PI", Text = "Piauí"},
 new SelectListItem { Value="RJ", Text = "Rio de Janeiro"},
 new SelectListItem { Value="RN", Text = "Rio Grande do Norte"},
 new SelectListItem { Value="RS", Text = "Rio Grande do Sul"},
 new SelectListItem { Value="RO", Text = "Rondônia"},
 new SelectListItem { Value="RR", Text = "Roraima"},
 new SelectListItem { Value="SC", Text = "Santa Catarina"},
 new SelectListItem { Value="SP", Text = "São Paulo"},
 new SelectListItem { Value="SE", Text = "Sergipe"},
 new SelectListItem { Value="TO", Text = "Tocantins"}
 };
 }
}

Startup.cs

One more thing, we will have to add some method calls (Dependency injection) in our Startup.cs , in the ConfigureServices method accessing this:

services
 .AddEntityFrameworkSqlite()
 .AddDbContextPool<Models.CrudDbContext>(o => o.UseSqlite("DataSource=crudnetcoremvc.db"));
  
using (var dbScope = services.BuildServiceProvider().GetService<Models.CrudDbContext>())
{
 dbScope.Database.EnsureCreated();
}
It should now look something like this:
public void ConfigureServices(IServiceCollection services)
{
 services.AddMvc();
 services
 .AddEntityFrameworkSqlite()
 .AddDbContextPool<Models.CrudDbContext>(o => o.UseSqlite("DataSource=crudnetcoremvc.db"));
  
 
using (var dbScope = services.BuildServiceProvider().GetService<Models.CrudDbContext>())
{
 dbScope.Database.EnsureCreated();
 }
}

_Layout.cshtml

To finish we will create the link in the file _Layout.cshtml to access the pages of clients and situations, the code of the file is this here:

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8" />
 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
 <title>@ViewData["Title"] - CrudBasicoNETCoreMVC</title>
  
 <environment include="Development">
 <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
 <link rel="stylesheet" href="~/css/site.css" />
 </environment>
 <environment exclude="Development">
 asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
 asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
 <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
 </environment>
  
</head>
<body>
 <nav class="navbar navbar-inverse navbar-fixed-top">
 <p class="container">
 <p class="navbar-header">
 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
 <span class="sr-only">Toggle navigation</span>
 <span class="icon-bar"></span>
 <span class="icon-bar"></span>
 <span class="icon-bar"></span>
 </button>
 <a asp-area="" asp-controller="Home"  asp-action="Index" class="navbar-brand">CrudBasicoNETCoreMVC</a>
 </p>
 <p class="navbar-collapse collapse">
 <ul class="nav navbar-nav">
 <li><a asp-area="" asp-controller="Clientes" asp-action="Index">Clientes</a></li>
<li><a asp-area="" asp-controller="Situacoes" asp-action="Index">Situação</a></li>
 </ul>
 </p>
 </p>
 </nav>
 <p class="container body-content">
 @RenderBody()
 <hr />
 <footer>
 <p>© 2017 - CrudBasicoNETCoreMVC</p>
 </footer>
 </p>
  
 <environment include="Development">
 <script src="~/lib/jquery/dist/jquery.js"></script>
 <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
 <script src="~/js/site.js" asp-append-version="true"></script>
 </environment>
 <environment exclude="Development">
 asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
 asp-fallback-test="window.jQuery"
 crossorigin="anonymous"
 integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
 </script>
 asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
 asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
 crossorigin="anonymous"
 integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
 </script>
 <script src="~/js/site.min.js" asp-append-version="true"></script>
 </environment>
</body>
</html>

Here's our final project running.

Download

Download link for the project:  https://gallery.technet.microsoft.com/Crud-Passo-a-Passo-AspNet-4287d07b