-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCurso .NETCore 3.1 ou NET5.0 - Criação de Projeto Passo a Passo.txt
672 lines (473 loc) · 23.1 KB
/
Curso .NETCore 3.1 ou NET5.0 - Criação de Projeto Passo a Passo.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
. Crie as pastas abaixo:
mkdir cursoApiNetcore
mkdir cursoApiNetcore/src
cd cursoApiNetcore
. Dentro da pasta src execute o comando abaixo:
cd src
dotnet new sln --name API
. Acesse o VSCode na pasta raiz do projeto:
cd cursoApiNetcore/src
code .
. Crie o arquivo global.json na pasta src com o conteúdo abaixo:
{
"sdk" : {
"version" : "5.0.17"
}
}
. Dentro da pasta src execute o comando abaixo:
cd cursoApiNetcore/src
dotnet new webapi -n application -o Api.Application --no-https -f net5.0
dotnet sln add Api.Application
dotnet build
. Dentro da pasta src acesse o VSCode, ao entrar ele irá fazer uma pergunta para colocar o build e o debug no projeto,
responda "Yes"
code .
. Ao responder "Yes", o VSCode ira criar uma pasta do projeto .vscode. Dentro desta pasta teremos dois arquivos
( launch.json e tasks.json). Esses arquivos criados automaticamente tem as configurações para depuração.
. Podemos acessar a execução do projeto do icone com triângulo na barra vertical do VSCode, que surgira a "Side Bar".
Neste ponto surgirá os botões de execução do projeto.
. Execute o projeto e no navegador execute a URL abaixo:
http://localhost:5000/WeatherForecast
. Acesse a pasta /src do seu projeto
. Digite o comando abaixo para criar a classlib:
dotnet new classlib -n Domain -o Api.Domain -f net5.0
. Dentro da pasta "src" digite o comando abaixo para adicionar a pasta "Api.Domain" a solution:
dotnet sln add ./Api.Domain/
dotnet restore
. Acesse a pasta Api.Domain e apague a classe Classe1.cs
. Digite o comando abaixo:
dotnet build
. Opções para o comando abaixo "Ctrl+Shift+B", ou acesse a opção "Terminal / Run Build Task"
. Acesse a pasta source e digite o comando abaixo:
cd src
dotnet new classlib -n CrossCutting -f net5.0 -o Api.CrossCutting
. Dentro da pasta "src" adicone a pasta CrossCutting a solution:
dotnet sln add ./Api.CrossCutting/
. Acesse a pasta Api.CrossCutting e apague a classe Classe1
dotnet build
. Acessar a pasta src e digitar o comando abaixo:
cd src
dotnet new classlib -n Data -f net5.0 -o Api.Data
. Dentro da pasta "src" adicone a pasta CrossCutting a solution:
dotnet sln add ./Api.Data/
. Acesse a pasta Api.Data e apague a classe Classe1
. Digite o comando abaixo:
dotnet build
. Acessar a pasta src e digitar o comando abaixo:
dotnet new classlib -n Service -f net5.0 -o Api.Service
. Dentro da pasta "src" adicone a pasta CrossCutting a solution:
dotnet sln add ./Api.Service/
. Acesse a pasta Api.Service e apague a classe Classe1
. Digite o comando abaixo:
dotnet build
. No VSCode, clique com o botão direito sobre a pasta Api.Domain e crie as folder abaixo:
Entities
Interfaces
. No VSCode, clique com o botão direito sobre a pasta Api.Domain.Entities e crie uma nova classe
com o nome de "BaseEntity" e com o conteúdo abaixo:
using System;
using System.ComponentModel.DataAnnotations;
namespace Api.Domain.Entities
{
public abstract class BaseEntity
{
[Key]
public Guid Id { get; set; }
private DateTime? _createAt;
public DateTime? CreateAt
{
get { return _createAt; }
set { _createAt = (value == null? DateTime.UtcNow : value); }
}
public DateTime? UpdateAt { get; set; }
}
}
. Acesse a pasta Api.Domain.Entities e crie a classe UserEntity.cs como abaixo:
namespace Api.Domain.Entities
{
[Table("User")]
public class UserEntity : BaseEntity
{
public string Nome { get; set; }
public string Email { get; set; }
}
}
. Acesse a pasta ./Api.Data e execute as linhas abaixo no prompt do sistema operacional:
dotnet add package Microsoft.EntityFrameworkCore --version 5.0.10
dotnet add package Microsoft.EntityFrameworkCore.Tools --version 5.0.5
dotnet add package Microsoft.EntityFrameworkCore.Design --version 5.0.5
dotnet add package Pomelo.EntityFrameworkCore.MySql --version 5.0.4
. Verifique se as tags abaixo estão no arquivo Api.Data.Data.csproj:
<ItemGroup>
<!-- <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.5" /> -->
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version=5.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
. Acesse a pasta /src/Api.Data e execute os comandos abaixo:
dotnet ef # Verificação se a ferramenta foi instalada com sucesso
dotnet restore
# Caso não exista a ferramenta "dotnet-ef" execute a linha abaixo
dotnet tool install --global dotnet-ef
dotnet build
. Verifique se depois do "build" a aplicação compilou com zero erro.
. Dentro da pasta Api.Data crie as pastas abaixo:
Content
Mapping
Repository
. No terminal e na pasta src faça a referência da pasta Api.Domain para a pasta Api.Data.
dotnet add ./Api.Data/ reference ./Api.Domain/
. Verifique no arquivo ./Api.Data/Data.csproj se existe uma referência ao projeto Api.Domain
. Crie a classe MyContext.cs dentro da pasta ./Api.Data/Context como abaixo. O contexto que fará a conexão
com o banco de dados.
using System;
using Api.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace Api.Data.Content
{
public class MyContext : DbContext
{
public DbSet<UserEntity> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseMySql("Server=localhost;Port=3306;Database=testdb;Uid=root;Pwd=root",
ServerVersion.AutoDetect("Server=localhost;Port=3306;Database=testdb;Uid=root;Pwd=root"));
}
}
. Crie na pasta "mapping" a classe "UserMap" como abaixo:
using Api.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Api.Data.Mapping
{
public class UserMap : IEntityTypeConfiguration<UserEntity>
{
public void Configure(EntityTypeBuilder<UserEntity> builder)
{
builder.ToTable("User");
builder.HasKey( u => u.Id );
builder.HasIndex( u => u.Email );
builder.Property( u => u.Nome )
.HasColumnName("Nome")
.HasColumnType("VARCHAR")
.HasMaxLength(60)
.IsRequired();
builder.Property( u => u.Email )
.HasColumnName("Email")
.HasColumnType("VARCHAR")
.HasMaxLength(100)
.IsRequired();
builder.Property( u => u.CreatedAt )
.HasColumnName("CreatedAt")
.HasColumnType("TIMESTAMP")
.HasDefaultValueSql("CURRENT_TIMESTAMP");
}
}
}
. Observações: O Engine EF do MySQL não se mostrou eficiente para criar a base. Nesse caso compensa mais criar
o script manualmente e executá-lo no banco:
CREATE DATABASE testdb;
USE testdb;
CREATE TABLE `User` (
`Id` int NOT NULL AUTO_INCREMENT,
`Nome` VARCHAR(100) CHARACTER SET utf8mb4 NULL,
`Email` VARCHAR(100) CHARACTER SET utf8mb4 NULL,
`CreatedAt` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
`UpdateAt` datetime(6) NULL,
CONSTRAINT `PK_Users` PRIMARY KEY (`Id`)
) CHARACTER SET utf8mb4;
. Acesse a classe Api.Data.Content.MyContext.cs e altere o método "OnModelCreating" como abaixo:
using Api.Data.Mapping;
using Api.Domain.Entities;
using Microsoft.EntityFrameworkCore;
namespace Api.Data.Content {
public class MyContext : DbContext
{
public DbSet<UserEntity> Users { get; set; }
public MyContext(DbContextOptions<MyContext> options) : base(options){ }
protected override void OnModelCreating(ModelBuilder modelBuilder){
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<UserEntity>( new UserMap().Configure ); // Linha incluída
}
}
}
. Na pasta raiz Api.Data digite os comandos abaixo para criação das tabelas no banco de dados:
# UserMigrations é o nome que é data para a migração
dotnet ef migrations add UserMigration
donet ef database update
. Crie a interface abaixo em Api.Domain.Interfaces
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Api.Domain.Entities;
namespace Api.Domain.Interfaces
{
public interface IRepository<T,K> where T: BaseEntity
{
Task<T> InsertAsync( T item);
Task<T> UpdateAsync( T item );
Task<bool> DeleteAsync(K id );
Task<T> SelectAsync( K id );
Task<IEnumerable<T>> SelectAsync();
Task<bool> ExistAsync( K id );
}
}
. Crie dentro da pasta Api.Data.Repository a classe BaseRepository como abaixo:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Api.Data.Content;
using Api.Domain.Entities;
using Api.Domain.Interfaces;
using Microsoft.EntityFrameworkCore;
namespace Api.Data.Repository
{
public class BaseRepository<T, K> : IRepository<T, K> where T : BaseEntity
{
protected readonly MyContext _context;
private DbSet<T> _dataSet;
public BaseRepository(MyContext context)
{
_context = context;
_dataSet = _context.Set<T>();
}
public async Task<bool> DeleteAsync(K id)
{
var result = await _dataSet.SingleOrDefaultAsync(p => p.Id.Equals(id));
if (result == null)
return false;
_dataSet.Remove(result);
await _context.SaveChangesAsync();
return true;
}
public async Task<T> InsertAsync(T item)
{
item.CreatedAt = DateTime.UtcNow;
_dataSet.Add(item);
await _context.SaveChangesAsync();
return item;
}
public async Task<IEnumerable<T>> SelectAsync()
{
return await _dataSet.ToListAsync();
}
public async Task<T> SelectAsync(K id)
{
return await _dataSet.SingleOrDefaultAsync(p => p.Id.Equals(id));
}
public async Task<T> UpdateAsync(T item)
{
var result = await _dataSet.SingleOrDefaultAsync(p => p.Id.Equals(item.Id));
if (result == null)
return null;
item.UpdateAt = DateTime.UtcNow;
item.CreatedAt = result.CreatedAt;
_context.Entry(result).CurrentValues.SetValues(item);
await _context.SaveChangesAsync();
return item;
}
public async Task<bool> ExistAsync(K id)
{
return await _dataSet.AnyAsync(p => p.Id.Equals(id));
}
}
}
. Dentro da pasta Api.Domain/Interface crie a pasta "Services".
. Dentro da nova pasta "Services" crie a pasta "User".
. No VSCode, clique com o botão direito sobre a pasta "User", escolha a opção "New C# Interface" e
dê o nome da interface de "IUserService".
. Copie o código abaixo para a interface IUserService:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Api.Domain.Entities;
namespace Api.Domain.Interfaces.Services.User
{
public interface IUserService
{
Task<UserEntity> Get(int id);
Task<IEnumerable<UserEntity>> GetAll();
Task<UserEntity> Post(UserEntity user);
Task<UserEntity> Put(UserEntity user);
Task<bool> Delete(int id);
}
}
. Vá ao terminal, na pasta "src" e execute o comando abaixo:
dotnet add ./Api.Service/ reference ./Api.Domain/
dotnet add ./Api.Service/ reference ./Api.Data/
dotnet add ./Api.Service/ reference ./Api.CrossCutting/
. Acesse o arquivo src/Api.Service/Service.cproj e verifique se as referências acima foram
inseridas corretamente neste arquivo.
. Na pasta "src" digite o comando abaixo no prompt do sistema operacional:
dotnet build
. Dentro da pasta Api.Service crie a pasta "Services" com clique direito no VSCode.
. No VSCode, clique com o botão direito sobre a nova pasta "Services", escolha a opção "New C# Class" e
dê o nome da interface de "UserService".
. Digite o código abaixo na classe UserService:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Api.Domain.Entities;
using Api.Domain.Interfaces;
using Api.Domain.Interfaces.Services.User;
namespace Api.Service.Services
{
public class UserService : IUserService // 1. 2.
{
private IRepository<UserEntity, int> _repository; // 3.
public UserService(IRepository<UserEntity, int> repository) // 4.
{
_repository = repository;
}
public Task<bool> Delete(int id)
{
throw new NotImplementedException();
}
public Task<UserEntity> Get(int id)
{
throw new NotImplementedException();
}
public async Task<IEnumerable<UserEntity>> GetAll()
{
return await _repository.SelectAsync();
}
public async Task<UserEntity> Post(UserEntity user)
{
return await _repository.InsertAsync(user);
}
public async Task<UserEntity> Put(UserEntity user)
{
return await _repository.UpdateAsync(user);
}
}
}
. Acesse a pasta src e digite o comando abaixo no prompt do sistema operacional:
dotnet add Api.Application reference Api.Domain
dotnet add Api.Application reference Api.Service
dotnet add Api.Application reference Api.CrossCutting
. Acesse a classe Api.Application.Application.csproj e verifique se as dependências foram incluidas com sucesso.
. O padrão de nomenclatura para se criar uma classe controller seria [nome do objeto] + Controller. Sem esse padrão
de nomenclatura o .Net não reconhece a classe como um controller.
. Crie a classe Api.Application.Controllers.UsersController com o código abaixo:
using System;
using System.Net;
using System.Threading.Tasks;
using Api.Domain.Entities;
using Api.Domain.Interfaces.Services.User;
using Microsoft.AspNetCore.Mvc;
namespace Api.Application.Controllers
{
//http://localhost:5000/api/users
[Route("api/[controller]")] // 2. O [controller] indica ao MVC que para ser chamado é necessário informar "users" que será associado a classe UserController
[ApiController]
public class UsersController : ControllerBase // 1. Interface ControllerBase contém todos os métodos de uma API
{
public IUserService _service { get; set; }
public UsersController(IUserService service)
{
_service = service;
}
[HttpGet]
public async Task<ActionResult> GetAll()
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState); // 400 Bad Request - Solicitação Inválida
}
try
{
return Ok(await _service.GetAll());
}
catch (ArgumentException e)
{
return StatusCode((int)HttpStatusCode.InternalServerError, e.Message);
}
}
[HttpGet]
[Route("{id}", Name = "GetWithId")]
public async Task<ActionResult> Get(int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
return Ok(await _service.Get(id));
}
catch (ArgumentException e)
{
return StatusCode((int)HttpStatusCode.InternalServerError, e.Message);
}
}
[HttpPost]
public async Task<ActionResult> Post([FromBody] UserEntity user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
var result = await _service.Post(user);
if (result != null)
{
return Created(new Uri(Url.Link("GetWithId", new { id = result.Id })), result);
}
else
{
return BadRequest();
}
}
catch (ArgumentException e)
{
return StatusCode((int)HttpStatusCode.InternalServerError, e.Message);
}
}
[HttpPut]
public async Task<ActionResult> Put([FromBody] UserEntity user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
var result = await _service.Put(user);
if (result != null)
{
return Ok(result);
}
else
{
return BadRequest();
}
}
catch (ArgumentException e)
{
return StatusCode((int)HttpStatusCode.InternalServerError, e.Message);
}
}
[HttpDelete("{id}")]
public async Task<ActionResult> Delete(int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
return Ok(await _service.Delete(id));
}
catch (ArgumentException e)
{
return StatusCode((int)HttpStatusCode.InternalServerError, e.Message);
}
}
}
}