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

Add lab 1 src starting point #3

Merged
merged 2 commits into from
Feb 5, 2024
Merged
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
4 changes: 2 additions & 2 deletions build/Build.proj
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
</PropertyGroup>

<ItemGroup>
<RepoSlns Include="$(MSBuildThisFileDirectory)../*.sln" />
<AppHostProjects Include="$(MSBuildThisFileDirectory)../src/**/*.AppHost/*.AppHost.csproj" />
<RepoSlns Include="$(MSBuildThisFileDirectory)../**/*.sln" />
<AppHostProjects Include="$(MSBuildThisFileDirectory)../**/*.AppHost/*.AppHost.csproj" />
</ItemGroup>

<Target Name="BuildRepoSlns" BeforeTargets="Build">
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>eShop.Catalog.Data.Manager</RootNamespace>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\Catalog.Data\Catalog.Data.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Aspire.Npgsql.EntityFrameworkCore.PostgreSQL" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<Compile Include="..\Shared\ActivityExtensions.cs" Link="Extensions\ActivityExtensions.cs" />
<Compile Include="..\Shared\MigrateDbContextExtensions.cs" Link="Extensions\MigrateDbContextExtensions.cs" />
</ItemGroup>

<ItemGroup>
<Folder Include="Migrations\" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Npgsql;

namespace eShop.Catalog.Data.Manager;

public partial class CatalogContextSeed(IWebHostEnvironment env, ILogger<CatalogContextSeed> logger)
: IDbSeeder<CatalogDbContext>
{
public async Task SeedAsync(CatalogDbContext context)
{
var contentRootPath = env.ContentRootPath;
var picturePath = env.WebRootPath;

// Workaround from https://github.com/npgsql/efcore.pg/issues/292#issuecomment-388608426
context.Database.OpenConnection();
((NpgsqlConnection)context.Database.GetDbConnection()).ReloadTypes();

if (!context.CatalogItems.Any())
{
var sourcePath = Path.Combine(contentRootPath, "Setup", "catalog.json");
var sourceJson = File.ReadAllText(sourcePath);
var sourceItems = JsonSerializer.Deserialize<CatalogSourceEntry[]>(sourceJson)
?? throw new InvalidOperationException($"Seed data file was found but it contained no data: '{sourcePath}'");

context.CatalogBrands.RemoveRange(context.CatalogBrands);
await context.CatalogBrands.AddRangeAsync(sourceItems.Select(x => x.Brand).Distinct()
.Select(brandName => new CatalogBrand { Brand = brandName }));
logger.LogInformation("Seeded catalog with {NumBrands} brands", context.CatalogBrands.Count());

context.CatalogTypes.RemoveRange(context.CatalogTypes);
await context.CatalogTypes.AddRangeAsync(sourceItems.Select(x => x.Type).Distinct()
.Select(typeName => new CatalogType { Type = typeName }));
logger.LogInformation("Seeded catalog with {NumTypes} types", context.CatalogTypes.Count());

await context.SaveChangesAsync();

var brandIdsByName = await context.CatalogBrands.ToDictionaryAsync(x => x.Brand, x => x.Id);
var typeIdsByName = await context.CatalogTypes.ToDictionaryAsync(x => x.Type, x => x.Id);

await context.CatalogItems.AddRangeAsync(sourceItems.Select(source => new CatalogItem
{
Id = source.Id,
Name = source.Name,
Description = source.Description,
Price = source.Price,
CatalogBrandId = brandIdsByName[source.Brand],
CatalogTypeId = typeIdsByName[source.Type],
AvailableStock = 100,
MaxStockThreshold = 200,
RestockThreshold = 10,
PictureFileName = $"{source.Id}.webp"
}));

logger.LogInformation("Seeded catalog with {NumItems} items", context.CatalogItems.Count());

await context.SaveChangesAsync();
}
}

private class CatalogSourceEntry
{
public int Id { get; set; }
public required string Type { get; set; }
public required string Brand { get; set; }
public required string Name { get; set; }
public required string Description { get; set; }
public decimal Price { 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
@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;

#nullable disable

Expand All @@ -10,31 +11,16 @@ public partial class Initial : Migration
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterDatabase();

migrationBuilder.EnsureSchema("catalog");

migrationBuilder.CreateSequence(
name: "catalog_brand_hilo",
schema: "catalog",
incrementBy: 10);

migrationBuilder.CreateSequence(
name: "catalog_hilo",
schema: "catalog",
incrementBy: 10);

migrationBuilder.CreateSequence(
name: "catalog_type_hilo",
schema: "catalog",
incrementBy: 10);
migrationBuilder.EnsureSchema(
name: "catalog");

migrationBuilder.CreateTable(
name: "CatalogBrand",
schema: "catalog",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false),
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Brand = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false)
},
constraints: table =>
Expand All @@ -47,7 +33,8 @@ protected override void Up(MigrationBuilder migrationBuilder)
schema: "catalog",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false),
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Type = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false)
},
constraints: table =>
Expand All @@ -60,11 +47,12 @@ protected override void Up(MigrationBuilder migrationBuilder)
schema: "catalog",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false),
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
Description = table.Column<string>(type: "text", nullable: true),
Description = table.Column<string>(type: "text", nullable: false),
Price = table.Column<decimal>(type: "numeric", nullable: false),
PictureFileName = table.Column<string>(type: "text", nullable: true),
PictureFileName = table.Column<string>(type: "text", nullable: false),
CatalogTypeId = table.Column<int>(type: "integer", nullable: false),
CatalogBrandId = table.Column<int>(type: "integer", nullable: false),
AvailableStock = table.Column<int>(type: "integer", nullable: false),
Expand All @@ -78,30 +66,36 @@ protected override void Up(MigrationBuilder migrationBuilder)
table.ForeignKey(
name: "FK_Catalog_CatalogBrand_CatalogBrandId",
column: x => x.CatalogBrandId,
principalTable: "CatalogBrand",
principalSchema: "catalog",
principalTable: "CatalogBrand",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Catalog_CatalogType_CatalogTypeId",
column: x => x.CatalogTypeId,
principalTable: "CatalogType",
principalSchema: "catalog",
principalTable: "CatalogType",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});

migrationBuilder.CreateIndex(
name: "IX_Catalog_CatalogBrandId",
table: "Catalog",
schema: "catalog",
table: "Catalog",
column: "CatalogBrandId");

migrationBuilder.CreateIndex(
name: "IX_Catalog_CatalogTypeId",
table: "Catalog",
schema: "catalog",
table: "Catalog",
column: "CatalogTypeId");

migrationBuilder.CreateIndex(
name: "IX_Catalog_Name",
schema: "catalog",
table: "Catalog",
column: "Name");
}

/// <inheritdoc />
Expand All @@ -118,18 +112,6 @@ protected override void Down(MigrationBuilder migrationBuilder)
migrationBuilder.DropTable(
name: "CatalogType",
schema: "catalog");

migrationBuilder.DropSequence(
name: "catalog_brand_hilo",
schema: "catalog");

migrationBuilder.DropSequence(
name: "catalog_hilo",
schema: "catalog");

migrationBuilder.DropSequence(
name: "catalog_type_hilo",
schema: "catalog");
}
}
}
Loading
Loading