I would like to make TenantId a part of my entity's composite key.
public class MyEntity: Entity, IMultiTenant { public Guid? TenantId { get; set; } public Guid EntityId { get; set; }
public object[]? GetKeys()
{
return new object[]? { TenantId, EntityId };
}
}
I did something like this in my app and I'm having trouble saving entites that should belong to the host now as EF core does not allowed keys to be nullable. It is not possible for me to make the entityid the sole key of the entity.
5 Answer(s)
-
0
To use TenantId as part of a composite key in an ABP entity, you must consider that EF Core does not allow nullable properties in primary keys. Since IMultiTenant.TenantId is nullable (to support host entities), making it part of a composite key will cause issues when TenantId is null (i.e., for host-owned entities).
If you define your entity as:
public class MyEntity : Entity, IMultiTenant { public Guid? TenantId { get; set; } public Guid EntityId { get; set; } public override object[] GetKeys() { return new object[] { TenantId, EntityId }; } }
You will encounter problems saving entities with a null TenantId, because EF Core does not support nullable columns in primary keys.
Workarounds:
- Use a single, non-nullable key (e.g., EntityId as the primary key).
- If you must use a composite key, ensure all parts are non-nullable. This would require making TenantId non-nullable, which breaks host/tenant separation in ABP.
- Alternatively, use a unique index (not a primary key) for (TenantId, EntityId) and keep EntityId as the primary key.
Example:
public class MyEntity : Entity<Guid>, IMultiTenant { public Guid? TenantId { get; set; } // EntityId is now the primary key (from Entity<Guid>) } // In your DbContext: protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.Entity<MyEntity>() .HasIndex(e => new { e.TenantId, e.Id }) .IsUnique(); }
This approach allows TenantId to be nullable and still enforces uniqueness for (TenantId, EntityId) without violating EF Core's primary key constraints.
Sources:
This response was generated by AI. If it didn’t solve your problem, feel free to post a new answer — our support team will jump in to help you soon.
-
0
The AI solution didnt really help
-
0
hi
EF core does not allowed keys to be nullable.
This is an EF Core(SQL) limitation. You can't do this.
Thanks.
-
0
what does you can do this mean
-
0
Sorry, I mean if EF Core(SQL) has this limitation. You can't do it.