Apply tenantId on every insert.
Hi, first of all thank you for this library. It makes query side of implementing multi tenancy very easy. I have a question regarding applying multi tenant on insert.
I was wondering if there was a way to set a tenantId on every insert? Currently, I have implemented this feature by overriding the saveChanges method see below.
public override int SaveChanges()
{
var entries = context
.ChangeTracker
.Entries<ITenant>()
.ToList();
foreach (var entityEntry in entries)
{
entityEntry.Property(m => m.TenantId).CurrentValue = _tenantId;
}
return base.SaveChanges();
}
But the problem I have with this is that the consumer must override SaveChanges method in dbcontext. Unlike the Filter extension method. The filter extension method can be applied outside of the dbcontext method.
Is there a similar way of achieving the saveChanges function using extension method?
Hello @john1452 ,
It's definitely possible to create a feature for this but unfortunately, we don't have the time on our side at this moment for such development.
So you will need to look if some other libraries already support this features
Best Regards,
Jonathan
Hi Jonathan,
Thanks for the reply. Off the top of your head, can you think of a way this can be implemented? I am just looking for a hint to start.
If I figure it out I will definitely submit a PR.
Hello @john1452 ,
Which version of Entity Framework are you using? Just to make sure that's possible ;)
Thanks Jonathan,
I am using Entity Framework Core 2.1.
Damn, it makes thing harder since EF Core has not added interceptor yet.
I'm not sure if that would be possible in EF Core.
Unless your users inherits from your context class or use your own version of the SaveChanges method as we do for SaveChanges(audit), it would be hard.
I believe the easiest way to start is to add an extension methods SaveChangesTenant (or whatever you call it). At least you will own the method and be able to do whatever you want.
If you find out a way to hook inside the SaveChanges method, I would be happy to know how.
Best Regards,
Jonathan
Thanks for your input Jonathan.
Looks like in 2.1 RC they have added events to change tracker.
I am going to play around with this for now.
Oh wow,
That will make TenantId, auditing field, soft deleted, etc. very easy to do with this event ;)
Thank a lot for sharing, I have added a note to look at it on my side.
Best Regards,
Jonathan