Can TenantId be set automatically when part of the PK using .IsMultiTenant().AdjustKey() ? #612
-
Imagine I am creating a new Blog in my database using Finbuckle and Per-Tenant EF Core. I find that if the new Blog has a PK of Id+TenantId, having used .IsMultiTenant().AdjustKey() in my model, I am forced to provide Blog.TenantId manually rather than relying on SaveChanges(). If I do not add TenantId to my model an exception is thrown:
The Tenant context is working correctly. Version is 6.9.0. Does AdjustKey() always require a TenantId and explicit set, or is there a pattern which avoids this? Also, when a shadow TenantId is added as a FK on the related BlogPosts entity, does this TenantId participate in QueryFiltering standalone? In other words, would BlogPosts in another tenant be found if the BlogPosts entity is not marked as MultiTenant? The docs are unclear on this and only explained that, "a FK may be added as a result of the PK". Thank you. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 4 replies
-
Hi, sorry I didn't see this sooner. There is a property on Regarding a related entity like |
Beta Was this translation helpful? Give feedback.
-
Thanks so much Andrew. I hadn't appreciated this use case for Overwrite until I got more familiar with the framework. I found that where I have an explicit TenantId property used in a compound PK I need to have a non-null default value set as an initial value, then rely on TenantNotSetMode.Overwrite to correct it on SaveChanges, as you say. In my case explicit TenantId is initially set to Guid.Empty.ToString(), EF attaching does not complain, and Finbuckle later corrects the TenantId on SaveChanges. Having seen your comments elsewhere however, I'm leaning towards dropping the compound key (by removing AdjustKey) on the basis I am using a GUID PK anyway. Possibly suffering a very slight loss of query performance based on independent indexes. But it's good to have both options, thank you. |
Beta Was this translation helpful? Give feedback.
-
Excellent. I'm glad it worked out for you and thank you for the sponsorship. |
Beta Was this translation helpful? Give feedback.
Hi, sorry I didn't see this sooner. There is a property on
MultiTenantDbContext
calledTenantNotSetMode
which you should be able to set toOverwrite
and it should set the tenant for you. Docs here.Regarding a related entity like
Posts
, the filtering doesn't apply there unfortunately -- this is a limitation of global query filters which this Finbuckle functionality it based on.