I have creation of tenant
Here is code
var tenant = new Tenant(tenancyName, name)
{
IsActive = isActive,
EditionId = editionId,
SubscriptionEndDateUtc = subscriptionEndDate?.ToUniversalTime(),
IsInTrialPeriod = isInTrialPeriod,
ConnectionString = connectionString.IsNullOrWhiteSpace()
? null
: SimpleStringCipher.Instance.Encrypt(connectionString)
};
await CreateAsync(tenant);
await _unitOfWorkManager.Current.SaveChangesAsync(); //To get new tenant's id.
tenancyName
can be duplicated
So for checking it I use this condition
if (await TenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenant.TenancyName) != null)
{
}
I need to add a count to it to be unique.
So for example, if EugeneTenant
is duplicated, I need to add 2 to it, to be EugeneTenant2
,
if EugeneTenant2 is duplicated, add 3 to it, so EugeneTenant3
So it will be autoincremented from 2 until the condition will meet.
I added this code
int startNumber = 2;
do
{
tenant.TenancyName = $"{tenant.TenancyName}{startNumber}";
tenant.Name = $"{tenant.TenancyName}{startNumber}";
startNumber++;
}
while (await TenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenant.TenancyName) != null);
But for Example if I have EugeneTenancy2
, next one I have, EugeneTenancy23
How I can do this?
2
Answers
If you would use a delimiter between the name and the counter (like
EugeneTenancy-2
) then you can get rid ofstartNumber
counter.Obviously this code is super fragile (
.Length == 1
,parts[1]
,int.Parse
, etc.) but you get the idea how to rely on a data, which is already available inside theTenancyName
.In other words this is not a robust code, it is created for demonstration purposes only.
UPDATE #1: If no delimiter is allowed
Then you need to use
TrimStart
instead