Skip to content

Commit 0f67aa5

Browse files
feat(BaseModel): add ID generator and entity annotations
- Implement snowflake ID generator for entity IDs - Add DataAnnotations for database mapping - Change debug profile from https to http in project settings
1 parent e60f206 commit 0f67aa5

File tree

3 files changed

+54
-2
lines changed

3 files changed

+54
-2
lines changed

Core/Entities/BaseModel/BaseModel.cs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
1+
using System.ComponentModel.DataAnnotations;
2+
using System.ComponentModel.DataAnnotations.Schema;
3+
14
namespace PaymentCoreServiceApi.Core.Entities.BaseModel;
25

36
public abstract class EntityBase
47
{
5-
public long Id { get; set; }
8+
[Key]
9+
[DatabaseGenerated(DatabaseGeneratedOption.None)]
10+
public long Id { get; init; } = IdGenerator.NextId();
611
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
712
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
813
public bool Active { get; set; } = true;
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
using System;
2+
using System.Threading;
3+
4+
public static class IdGenerator
5+
{
6+
private static readonly long MachineId = 1; // có thể config theo server
7+
private static long lastTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
8+
private static long sequence = 0;
9+
10+
public static long NextId()
11+
{
12+
while (true)
13+
{
14+
var timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
15+
var last = Volatile.Read(ref lastTimestamp);
16+
17+
if (timestamp < last)
18+
{
19+
Thread.Sleep(1);
20+
continue;
21+
}
22+
23+
long nextSequence;
24+
if (timestamp == last)
25+
{
26+
nextSequence = (Interlocked.Increment(ref sequence)) & 4095;
27+
if (nextSequence == 0)
28+
{
29+
SpinWait.SpinUntil(() =>
30+
DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() > timestamp);
31+
continue;
32+
}
33+
}
34+
else
35+
{
36+
Interlocked.Exchange(ref sequence, 0);
37+
Volatile.Write(ref lastTimestamp, timestamp);
38+
nextSequence = 0;
39+
}
40+
41+
return ((timestamp << 22) | (MachineId << 12) | nextSequence);
42+
}
43+
}
44+
}

PaymentCoreServiceApi.csproj.user

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
<?xml version="1.0" encoding="utf-8"?>
22
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
33
<PropertyGroup>
4-
<ActiveDebugProfile>https</ActiveDebugProfile>
4+
<ActiveDebugProfile>http</ActiveDebugProfile>
5+
</PropertyGroup>
6+
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
7+
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
58
</PropertyGroup>
69
</Project>

0 commit comments

Comments
 (0)