Skip to content

Commit 9bedbb3

Browse files
mysql sample
1 parent 99e511b commit 9bedbb3

File tree

8 files changed

+261
-0
lines changed

8 files changed

+261
-0
lines changed

5_More/EFCore/MySQL/Book.cs

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
using System.ComponentModel.DataAnnotations;
2+
3+
namespace DataSample;
4+
5+
public class Book
6+
{
7+
public Book(string title, string? publisher = default, int bookId = default)
8+
{
9+
Title = title;
10+
Publisher = publisher;
11+
BookId = bookId;
12+
}
13+
[StringLength(50)]
14+
public string Title { get; set; }
15+
[StringLength(30)]
16+
public string? Publisher { get; set; }
17+
public int BookId { get; set; }
18+
}

5_More/EFCore/MySQL/BooksContext.cs

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
namespace DataSample;
2+
3+
public class BooksContext : DbContext
4+
{
5+
public BooksContext(DbContextOptions<BooksContext> options)
6+
: base(options) { }
7+
8+
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
9+
{
10+
base.OnConfiguring(optionsBuilder);
11+
}
12+
13+
public DbSet<Book> Books => Set<Book>();
14+
}

5_More/EFCore/MySQL/MySQL.csproj

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net6.0</TargetFramework>
6+
<Nullable>enable</Nullable>
7+
<ImplicitUsings>enable</ImplicitUsings>
8+
<UserSecretsId>07a68fc9-d84f-4135-b58b-df0b491130ad</UserSecretsId>
9+
</PropertyGroup>
10+
11+
<ItemGroup>
12+
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.5" />
13+
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.5">
14+
<PrivateAssets>all</PrivateAssets>
15+
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
16+
</PackageReference>
17+
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
18+
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.1" />
19+
</ItemGroup>
20+
21+
<ItemGroup>
22+
<None Update="appsettings.json">
23+
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
24+
</None>
25+
</ItemGroup>
26+
27+
</Project>

5_More/EFCore/MySQL/MySQL.sln

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 17
4+
VisualStudioVersion = 17.3.32505.426
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MySQL", "MySQL.csproj", "{B1EBC483-D5E6-400A-8482-1CE79950F122}"
7+
EndProject
8+
Global
9+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
10+
Debug|Any CPU = Debug|Any CPU
11+
Release|Any CPU = Release|Any CPU
12+
EndGlobalSection
13+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
14+
{B1EBC483-D5E6-400A-8482-1CE79950F122}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15+
{B1EBC483-D5E6-400A-8482-1CE79950F122}.Debug|Any CPU.Build.0 = Debug|Any CPU
16+
{B1EBC483-D5E6-400A-8482-1CE79950F122}.Release|Any CPU.ActiveCfg = Release|Any CPU
17+
{B1EBC483-D5E6-400A-8482-1CE79950F122}.Release|Any CPU.Build.0 = Release|Any CPU
18+
EndGlobalSection
19+
GlobalSection(SolutionProperties) = preSolution
20+
HideSolutionNode = FALSE
21+
EndGlobalSection
22+
GlobalSection(ExtensibilityGlobals) = postSolution
23+
SolutionGuid = {C8129E93-3E59-4153-8699-DFDE9D38C492}
24+
EndGlobalSection
25+
EndGlobal

5_More/EFCore/MySQL/Program.cs

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
global using Microsoft.EntityFrameworkCore;
2+
3+
using Microsoft.Extensions.Configuration;
4+
using Microsoft.Extensions.DependencyInjection;
5+
using Microsoft.Extensions.Hosting;
6+
using DataSample;
7+
8+
using var host = Host.CreateDefaultBuilder(args)
9+
.ConfigureServices((context, services) =>
10+
{
11+
var connectionString = context.Configuration.GetConnectionString("MySQLConnection");
12+
if (connectionString is null)
13+
{
14+
throw new InvalidOperationException("MySQLConnection is not configured");
15+
}
16+
ServerVersion serverVersion = ServerVersion.AutoDetect(connectionString);
17+
services.AddDbContext<BooksContext>(options =>
18+
{
19+
options.UseMySql(connectionString, serverVersion);
20+
});
21+
services.AddScoped<Runner>();
22+
})
23+
.Build();
24+
25+
await using var scope = host.Services.CreateAsyncScope();
26+
var runner = scope.ServiceProvider.GetRequiredService<Runner>();
27+
28+
await runner.CreateTheDatabaseAsync();
29+
await runner.AddBookAsync("Professional C# and .NET", "Wrox Press");
30+
await runner.AddBooksAsync();
31+
await runner.ReadBooksAsync();
32+
await runner.QueryBooksAsync();
33+
await runner.UpdateBookAsync();
34+
await runner.DeleteBooksAsync();
35+
await runner.DeleteDatabaseAsync();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"profiles": {
3+
"MySQL": {
4+
"commandName": "Project",
5+
"environmentVariables": {
6+
"DOTNET_ENVIRONMENT": "Development"
7+
}
8+
}
9+
}
10+
}

5_More/EFCore/MySQL/Runner.cs

+123
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
namespace DataSample;
2+
3+
public class Runner
4+
{
5+
private readonly BooksContext _booksContext;
6+
public Runner(BooksContext booksContext)
7+
{
8+
_booksContext = booksContext;
9+
}
10+
11+
public async Task CreateTheDatabaseAsync()
12+
{
13+
bool created = await _booksContext.Database.EnsureCreatedAsync();
14+
string creationInfo = created ? "created" : "exists";
15+
Console.WriteLine($"database {creationInfo}");
16+
}
17+
18+
public async Task DeleteDatabaseAsync()
19+
{
20+
Console.Write("Delete the database? (y|n) ");
21+
string? input = Console.ReadLine();
22+
if (input?.ToLower() == "y")
23+
{
24+
bool deleted = await _booksContext.Database.EnsureDeletedAsync();
25+
string deletionInfo = deleted ? "deleted" : "not deleted";
26+
Console.WriteLine($"database {deletionInfo}");
27+
}
28+
}
29+
30+
public async Task AddBookAsync(string title, string publisher)
31+
{
32+
Book book = new(title, publisher);
33+
await _booksContext.Books.AddAsync(book);
34+
int records = await _booksContext.SaveChangesAsync();
35+
Console.WriteLine($"{records} record added with id {book.BookId}");
36+
37+
Console.WriteLine();
38+
}
39+
40+
public async Task AddBooksAsync()
41+
{
42+
Book b1 = new("Professional C# 7 and .NET Core 2", "Wrox Press");
43+
Book b2 = new("Professional C# 6 and .NET Core 1.0", "Wrox Press");
44+
Book b3 = new("Professional C# 5 and .NET 4.5.1", "Wrox Press");
45+
Book b4 = new("Essential Algorithms", "Wiley");
46+
await _booksContext.Books.AddRangeAsync(b1, b2, b3, b4);
47+
int records = await _booksContext.SaveChangesAsync();
48+
Console.WriteLine($"{records} records added");
49+
50+
Console.WriteLine();
51+
}
52+
53+
public async Task ReadBooksAsync(CancellationToken token = default)
54+
{
55+
#if DEBUG
56+
string query = _booksContext.Books.ToQueryString();
57+
Console.WriteLine(query);
58+
#endif
59+
List<Book> books = await _booksContext.Books.ToListAsync(token);
60+
foreach (var b in books)
61+
{
62+
Console.WriteLine($"{b.Title} {b.Publisher}");
63+
}
64+
65+
Console.WriteLine();
66+
}
67+
68+
public async Task QueryBooksAsync(CancellationToken token = default)
69+
{
70+
string query = _booksContext.Books.Where(b => b.Publisher == "Wrox Press").ToQueryString();
71+
Console.WriteLine(query);
72+
await _booksContext.Books
73+
.Where(b => b.Publisher == "Wrox Press")
74+
.ForEachAsync(b =>
75+
{
76+
Console.WriteLine($"{b.Title} {b.Publisher}");
77+
}, token);
78+
79+
Console.WriteLine();
80+
}
81+
82+
#if USERECORDS
83+
public async Task UpdateBookAsync()
84+
{
85+
Book? book = await _booksContext.Books.FindAsync(1);
86+
87+
if (book != null)
88+
{
89+
// detach the existing object from the context which allows to attach it with the Update method
90+
_booksContext.Entry(book).State = EntityState.Detached;
91+
Book bookUpdate = book with { Title = "Professional C# and .NET - 2021 Edition" };
92+
_booksContext.Update(bookUpdate);
93+
int records = await _booksContext.SaveChangesAsync();
94+
Console.WriteLine($"{records} record updated");
95+
96+
}
97+
Console.WriteLine();
98+
}
99+
#else
100+
public async Task UpdateBookAsync()
101+
{
102+
Book? book = _booksContext.Books.Find(1);
103+
104+
if (book != null)
105+
{
106+
book.Title = "Professional C# and .NET - 2021 Edition";
107+
int records = await _booksContext.SaveChangesAsync();
108+
Console.WriteLine($"{records} record updated");
109+
}
110+
Console.WriteLine();
111+
}
112+
#endif
113+
114+
public async Task DeleteBooksAsync()
115+
{
116+
List<Book> books = await _booksContext.Books.ToListAsync();
117+
_booksContext.Books.RemoveRange(books);
118+
int records = await _booksContext.SaveChangesAsync();
119+
Console.WriteLine($"{records} records deleted");
120+
121+
Console.WriteLine();
122+
}
123+
}

5_More/EFCore/MySQL/appsettings.json

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"Logging": {
3+
"Console": {
4+
"LogLevel": {
5+
"Microsoft.EntityFramework": "Debug"
6+
}
7+
}
8+
}
9+
}

0 commit comments

Comments
 (0)