[英]Entity framework core multi tenant : auto increment column based in another column value
Using entity framework core 6 with sample class使用带有示例 class 的实体框架核心 6
public class Sample
{
[Key]
public long Id { get; set; }
public long TenantId { get; set; }
public long PartitionId { get; set; }
}
I need to make auto increment of partition id based in brand id.我需要根据品牌 ID 自动增加分区 ID。
First I add index mapper between tenantId and partitionId to make sure never duplicated than i used in partitionId ValueGeneratedOnAdd()
function, my missing part how i can make auto generation of partitionId foreach tenantId in sequence.首先,我在 tenantId 和 partitionId 之间添加索引映射器,以确保不会重复我在 partitionId
ValueGeneratedOnAdd()
function 中使用的内容,我缺少的部分是如何按顺序为每个 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);
});
Required result should be like this要求的结果应该是这样的
Id | TenantId | PartitionId
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
4 | 2 | 2
You can achieve this by having a difference sequence for each tenant and you script it as part of the tenant onboarding.您可以通过为每个租户设置不同的顺序并将其编写为租户入职的一部分来实现这一点。
ex: When you create a tenant, you run the following script:例如:创建租户时,运行以下脚本:
CREATE SEQUENCE [dbo].[Tenant{0}_PartionIdSequence] AS [int] START WITH 1 INCREMENT BY 1
When you insert ar ecord to the sample table, you will have to call this script tp get the next value for PartitionId当您将 ar ecord 插入示例表时,您将必须调用此脚本 tp 获取 PartitionId 的下一个值
SELECT NEXT VALUE FOR dbo.[Tenant{0}_PartionIdSequence]
This way every tenant should have its own sequence这样每个租户都应该有自己的顺序
Not working, sequence has been created please note i'm using Postgres SQL, SELECT NEXT VALUE FOR
statement not correct syntax in my case.不工作,序列已创建请注意我使用的是 Postgres
SELECT NEXT VALUE FOR
语句在我的情况下语法不正确。
Please find below my changes.请在下面找到我的更改。
// 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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.