使用实体框架核心 6 和示例类
public class Sample
{
[Key]
public long Id { get; set; }
public long TenantId { get; set; }
public long PartitionId { get; set; }
}
我需要根据品牌id自动递增分区id。
首先,我在tenantId和partitionId之间添加索引映射器,以确保永远不会比我在partitionId
ValueGeneratedOnAdd()
函数中使用的重复,我缺少的部分是如何按顺序自动生成每个tenantId的partitionId。
modelBuilder.Entity<Sample>(builder =>
{
// enable unique partion id based in tenant level
builder.HasIndex(r => new { r.PartitionId, r.TenantId }).HasDatabaseName("IX_Sample_PartitionId").IsUnique();
builder.ToTable("Sample").Property(p => p.Id).HasColumnOrder(0);
builder.ToTable("Sample").Property(p => p.TenantId ).HasColumnOrder(1);
// create auto increment base in brand id
builder.ToTable("Sample").Property(p => p.PartitionId).ValueGeneratedOnAdd().HasColumnOrder(2);
});
需要的结果应该是这样的
Id | TenantId | PartitionId
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
4 | 2 | 2
您可以通过为每个租户设置不同的顺序并将其编写脚本作为租户入职的一部分来实现此目的。
例如: 创建租户时,运行以下脚本:
CREATE SEQUENCE [dbo].[Tenant{0}_PartionIdSequence] AS [int] START WITH 1 INCREMENT BY 1
当您将 ar ecord 插入示例表时,您必须调用此脚本来获取 PartitionId 的下一个值
SELECT NEXT VALUE FOR dbo.[Tenant{0}_PartionIdSequence]
这样每个租户都应该有自己的顺序
不起作用,序列已创建 请注意,我使用的是 Postgres SQL,
SELECT NEXT VALUE FOR
语句在我的情况下语法不正确。
请在下面找到我的更改。
// create sequence for partition id and map it in tenant level
modelBuilder.HasSequence<long>("Tenant{0}_PartitionId_seq")
.StartsAt(1)
.IncrementsBy(1);
modelBuilder.Entity<Sample>(builder =>
{
// enable unique partion id based in tenant level
builder.HasIndex(r => new { r.PartitionId, r.TenantId })
.HasDatabaseName("IX_Sample_PartitionId")
.IsUnique();
builder.ToTable("Sample").Property(p => p.Id).HasColumnOrder(0);
builder.ToTable("Sample").Property(p => p.TenantId).HasColumnOrder(1);
// mapping sequence table which consider tenant id
builder.ToTable("Sample").Property(p => p.PartitionId)
.HasDefaultValueSql("nextval('\"Tenant{0}_PartitionId_seq\"')")
.HasColumnOrder(2);
});