![](/img/trans.png)
[英]How to auto increment a column using an Entity Framework core in memory database?
[英]Entity framework core multi tenant : auto increment column based in another column value
使用带有示例 class 的实体框架核心 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()
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);
});
要求的结果应该是这样的
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 插入示例表时,您将必须调用此脚本 tp 获取 PartitionId 的下一个值
SELECT NEXT VALUE FOR dbo.[Tenant{0}_PartionIdSequence]
这样每个租户都应该有自己的顺序
不工作,序列已创建请注意我使用的是 Postgres 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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.