使用 PostgreSQL 数据库存储数据

This commit is contained in:
hello 2024-03-02 09:07:40 +08:00
parent 5e74bc50a9
commit 14b419dbf7
12 changed files with 270 additions and 0 deletions

View File

@ -0,0 +1,7 @@
namespace HelloShop.IdentityService.Constants
{
public class DbConstants
{
public const string ConnectionStringName = "IdentityDatabase";
}
}

View File

@ -0,0 +1,36 @@
using HelloShop.IdentityService.Entities;
using HelloShop.IdentityService.EntityFrameworks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace HelloShop.IdentityService.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UsersController(IdentityServiceDbContext dbContext) : ControllerBase
{
[HttpGet]
public IEnumerable<User> Get()
{
return dbContext.Set<User>();
}
// GET api/<UsersController>/5
[HttpGet("{id}")]
public User? Get(int id)
{
return dbContext.Set<User>().Find(id);
}
// POST api/<UsersController>
[HttpPost]
public void Post([FromBody] User value)
{
value.CreationTime = DateTimeOffset.Now;
dbContext.Add(value);
dbContext.SaveChanges();
}
}
}

View File

@ -0,0 +1,13 @@
namespace HelloShop.IdentityService.Entities
{
public class User
{
public int Id { get; set; }
public string UserName { get; set; } = default!;
public string PasswordHash { get; set; } = default!;
public DateTimeOffset CreationTime { get; set; } = DateTimeOffset.UtcNow;
}
}

View File

@ -0,0 +1,20 @@
using HelloShop.IdentityService.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace HelloShop.IdentityService.EntityFrameworks.EntityConfigurations
{
public class UserEntityTypeConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.ToTable("Users");
builder.HasKey(u => u.Id);
builder.Property(u => u.Id).HasColumnOrder(1);
builder.Property(u => u.UserName).HasMaxLength(50).HasColumnOrder(3);
builder.Property(u => u.PasswordHash).HasMaxLength(100).HasColumnOrder(2);
}
}
}

View File

@ -0,0 +1,18 @@
using Microsoft.EntityFrameworkCore;
using System.Reflection;
namespace HelloShop.IdentityService.EntityFrameworks
{
public class IdentityServiceDbContext(DbContextOptions<IdentityServiceDbContext> options) : DbContext(options)
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
}
}
}

View File

@ -0,0 +1,59 @@
// <auto-generated />
using System;
using HelloShop.IdentityService.EntityFrameworks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace HelloShop.IdentityService.EntityFrameworks.Migrations
{
[DbContext(typeof(IdentityServiceDbContext))]
[Migration("20240302004354_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("HelloShop.IdentityService.Entities.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasColumnOrder(1);
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTimeOffset>("CreationTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("PasswordHash")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)")
.HasColumnOrder(2);
b.Property<string>("UserName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)")
.HasColumnOrder(3);
b.HasKey("Id");
b.ToTable("Users", (string)null);
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,38 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace HelloShop.IdentityService.EntityFrameworks.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
PasswordHash = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
UserName = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
CreationTime = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Users");
}
}
}

View File

@ -0,0 +1,56 @@
// <auto-generated />
using System;
using HelloShop.IdentityService.EntityFrameworks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace HelloShop.IdentityService.EntityFrameworks.Migrations
{
[DbContext(typeof(IdentityServiceDbContext))]
partial class IdentityServiceDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("HelloShop.IdentityService.Entities.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasColumnOrder(1);
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTimeOffset>("CreationTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("PasswordHash")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)")
.HasColumnOrder(2);
b.Property<string>("UserName")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)")
.HasColumnOrder(3);
b.HasKey("Id");
b.ToTable("Users", (string)null);
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,6 @@
```shell
dotnet ef database drop --force
dotnet ef migrations remove
dotnet ef migrations add InitialCreate --output-dir EntityFrameworks/Migrations
dotnet ef database update
```

View File

@ -6,6 +6,11 @@
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>
<ItemGroup>

View File

@ -1,3 +1,7 @@
using HelloShop.IdentityService.Constants;
using HelloShop.IdentityService.EntityFrameworks;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.AddServiceDefaults();
@ -9,6 +13,11 @@ builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<IdentityServiceDbContext>(options =>
{
options.UseNpgsql(builder.Configuration.GetConnectionString(DbConstants.ConnectionStringName));
});
var app = builder.Build();
app.MapDefaultEndpoints();

View File

@ -5,5 +5,8 @@
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"IdentityDatabase": "Host=localhost;Port=5432;Database=IdentityService;Username=postgres;Password=postgres"
},
"AllowedHosts": "*"
}