-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Cria post, categoria e autor no banco de dados
O uso do EF facilita a criação de dados relacionados, com uma única instrução de adição, no conjunto principal, todos os itens relacionados são persistidos no banco e, ainda, gerenciando transação de forma automatizada.
- Loading branch information
1 parent
19eaf9b
commit 68d485d
Showing
1 changed file
with
27 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,32 @@ | ||
using Blog.Data; | ||
using Microsoft.EntityFrameworkCore; | ||
using Blog.Models; | ||
|
||
using var context = new BlogDataContext(); | ||
|
||
var tag = context | ||
.Tags | ||
.AsNoTracking() | ||
// First() - Retorna primeiro elemento ou exception quando condição não | ||
// satisfeita | ||
// FirstOrDefault() - Retorna primeiro elemento ou null quando condição | ||
// não satisfeita | ||
// Single() - Retorna único elemento ou exceção quando condição não | ||
// satisfeita ou mais de um | ||
// SingleOrDefault() - Retorna único elemento ou null quando condição | ||
// não satisfeita ou exception quando mais elements satisfazem a condição | ||
.SingleOrDefault(it => it.Id == 3); | ||
var user = new User | ||
{ | ||
Name = "André Baltieri", | ||
Slug = "andrebaltieri", | ||
Email = "[email protected]", | ||
Bio = "9x Microsoft MVP", | ||
Image = "https://balta.io", | ||
PasswordHash = "123098457" | ||
}; | ||
|
||
var category = new Category { Title = "Backend", Slug = "backend" }; | ||
|
||
var post = new Post | ||
{ | ||
Author = user, | ||
Category = category, | ||
Body = "<p>Hello world</p>", | ||
Slug = "comecando-com-ef-core", | ||
Summary = "Neste artigo vamos aprender EF core", | ||
Title = "Começando com EF Core", | ||
CreateDate = DateTime.Now, | ||
LastUpdateDate = DateTime.Now, | ||
}; | ||
|
||
context.Posts.Add(post); | ||
context.SaveChanges(); | ||
|
||
Console.WriteLine(tag?.Name); |