Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Value before save

I was wondering if there is any way to set a value to an entity onsave?
Because I'm working on a multi tenant web application and I would like to set the the current tenant ID (through simple DI service).

I tried using HasDefaultValue() in Fluent API, however this will try to convert to a SQL function. So this doesn't work for me.

builder.Entity<Order>( )
    .HasQueryFilter(p => p.TenantId == _tenantProvider.GetTenantId())
    .Property(p => p.TenantId)
    .HasDefaultValue(_tenantProvider.GetTenantId());

Any suggestions are greatly appreciated.

like image 442
matt350 Avatar asked Jan 01 '23 16:01

matt350


1 Answers

You could override the DbContext.SaveChanges() method and iterate the ChangeTracker entries:

public override int SaveChanges()
{
    foreach (var entityEntry in ChangeTracker.Entries()) // Iterate all made changes
    {
        if (entityEntry.Entity is Order order)
        {
            if (entityEntry.State == EntityState.Added) // If you want to update TenantId when Order is added
            {
                order.TenantId = _tenantProvider.GetTenantId();
            }
            else if (entityEntry.State == EntityState.Modified) // If you want to update TenantId when Order is modified
            {
                order.TenantId = _tenantProvider.GetTenantId();
            }
        }
    }
    return base.SaveChanges();
}

Of course, this needs the tenant provider to be injected into your context.

like image 149
kaffekopp Avatar answered Jan 04 '23 15:01

kaffekopp