Skip to content

Commit 8e21a4a

Browse files
committed
- Refactored code using PrimaryAlias to use PrimaryAliasId in cases where only the alias Id was needed, avoiding full navigation property loading. This change addresses issues where lazy-loading Person.PrimaryAlias caused exceptions (e.g., Person.Logic.cs:line 1003) tied to missing context during alias access.
1 parent 1c11165 commit 8e21a4a

File tree

12 files changed

+91
-41
lines changed

12 files changed

+91
-41
lines changed

Rock/Data/DbContext.cs

Lines changed: 66 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -336,13 +336,13 @@ public virtual SaveChangesResult SaveChanges( SaveChangesArgs args )
336336

337337
SaveErrorMessages = new List<string>();
338338

339-
// Try to get the current person alias and id
340-
PersonAlias personAlias = GetCurrentPersonAlias();
339+
// Try to get the current person alias id
340+
var personAliasId = GetCurrentPersonAliasId();
341341

342342
bool enableAuditing = GlobalAttributesCache.Value( "EnableAuditing" ).AsBoolean();
343343

344344
// Evaluate the current context for items that have changes
345-
var updatedItems = RockPreSave( this, personAlias, enableAuditing );
345+
var updatedItems = RockPreSave( this, personAliasId, enableAuditing );
346346

347347
// If update was not cancelled by triggered workflow
348348
if ( updatedItems != null )
@@ -364,7 +364,7 @@ public virtual SaveChangesResult SaveChanges( SaveChangesArgs args )
364364
// If any items changed process audit and triggers
365365
if ( updatedItems.Any() )
366366
{
367-
RockPostSave( updatedItems, personAlias, enableAuditing );
367+
RockPostSave( updatedItems, enableAuditing );
368368

369369
if ( args.IsAchievementsEnabled )
370370
{
@@ -428,7 +428,9 @@ private int SaveChangesInternal()
428428
/// <summary>
429429
/// Gets the current person alias.
430430
/// </summary>
431-
/// <returns></returns>
431+
/// <returns>The primary alias</returns>
432+
[Obsolete( "Use GetCurrentPersonAliasId() instead." )]
433+
[RockObsolete( "18.0" )]
432434
internal PersonAlias GetCurrentPersonAlias()
433435
{
434436
if ( HttpContext.Current != null && HttpContext.Current.Items.Contains( "CurrentPerson" ) )
@@ -448,21 +450,52 @@ internal PersonAlias GetCurrentPersonAlias()
448450
return null;
449451
}
450452

453+
/// <summary>
454+
/// Gets the current person alias Id.
455+
/// </summary>
456+
/// <returns>The Id of the current person's primary alias.</returns>
457+
internal int? GetCurrentPersonAliasId()
458+
{
459+
if ( HttpContext.Current != null && HttpContext.Current.Items.Contains( "CurrentPerson" ) )
460+
{
461+
var currentPerson = HttpContext.Current.Items["CurrentPerson"] as Person;
462+
if ( currentPerson != null && currentPerson.PrimaryAliasId != null )
463+
{
464+
return currentPerson.PrimaryAliasId;
465+
}
466+
}
467+
468+
if ( Net.RockRequestContextAccessor.Current != null )
469+
{
470+
return Net.RockRequestContextAccessor.Current.CurrentPerson?.PrimaryAliasId;
471+
}
472+
473+
return null;
474+
}
475+
451476
/// <summary>
452477
/// Updates the Created/Modified data for any model being created or modified
453478
/// </summary>
454479
/// <param name="dbContext">The database context.</param>
455480
/// <param name="personAlias">The person alias.</param>
456481
/// <param name="enableAuditing">if set to <c>true</c> [enable auditing].</param>
457482
/// <returns></returns>
483+
[Obsolete( "Use RockPreSave( DbContext dbContext, int? PersonAliasId, bool enableAuditing ) instead." )]
484+
[RockObsolete( "18.0" )]
458485
protected virtual List<ContextItem> RockPreSave( DbContext dbContext, PersonAlias personAlias, bool enableAuditing = false )
459486
{
460-
int? personAliasId = null;
461-
if ( personAlias != null )
462-
{
463-
personAliasId = personAlias.Id;
464-
}
487+
return RockPreSave( dbContext, personAlias?.Id, enableAuditing );
488+
}
465489

490+
/// <summary>
491+
/// Updates the Created/Modified data for any model being created or modified
492+
/// </summary>
493+
/// <param name="dbContext">The database context.</param>
494+
/// <param name="personAliasId">The person alias Id.</param>
495+
/// <param name="enableAuditing">if set to <c>true</c> [enable auditing].</param>
496+
/// <returns></returns>
497+
protected virtual List<ContextItem> RockPreSave( DbContext dbContext, int? personAliasId, bool enableAuditing = false )
498+
{
466499
// This triggers the change detection, so it must be called before
467500
// we check for the implied relationship changes.
468501
var entries = dbContext.ChangeTracker.Entries().ToList();
@@ -540,7 +573,7 @@ c.Entity is IEntity &&
540573
// instead of passing "true" the trigger model and UI would support a
541574
// on-value-changed checkbox (or perhaps it should be the default/only behavior)
542575
// and its value would be passed in to the onValueChange
543-
if ( !TriggerWorkflows( contextItem, WorkflowTriggerType.PreSave, personAlias ) )
576+
if ( !TriggerWorkflows( contextItem, WorkflowTriggerType.PreSave ) )
544577
{
545578
// If any workflow has aborted the save operation
546579
// then let all the save hooks know the save was
@@ -596,7 +629,7 @@ c.Entity is IEntity &&
596629
}
597630
else if ( entry.State == EntityState.Deleted )
598631
{
599-
if ( !TriggerWorkflows( contextItem, WorkflowTriggerType.PreDelete, personAlias ) )
632+
if ( !TriggerWorkflows( contextItem, WorkflowTriggerType.PreDelete ) )
600633
{
601634
// Let all the hooks that were called know that
602635
// the save was aborted.
@@ -652,9 +685,21 @@ this play vital role in displaying the Who column in history summary.
652685
/// Creates audit logs and/or triggers workflows for items that were changed
653686
/// </summary>
654687
/// <param name="updatedItems">The updated items.</param>
655-
/// <param name="personAlias">The person alias.</param>
688+
/// <param name="personAlias">The person alias (NOT USED; hasn't been used in years).</param>
656689
/// <param name="enableAuditing">if set to <c>true</c> [enable auditing].</param>
690+
[Obsolete( "Use RockPostSave( List<ContextItem> updatedItems, bool enableAuditing = false ) instead." )]
691+
[RockObsolete( "18.0" )]
657692
protected virtual void RockPostSave( List<ContextItem> updatedItems, PersonAlias personAlias, bool enableAuditing = false )
693+
{
694+
RockPostSave( updatedItems, enableAuditing );
695+
}
696+
697+
/// <summary>
698+
/// Creates audit logs and/or triggers workflows for items that were changed
699+
/// </summary>
700+
/// <param name="updatedItems">The updated items.</param>
701+
/// <param name="enableAuditing">if set to <c>true</c> [enable auditing].</param>
702+
protected virtual void RockPostSave( List<ContextItem> updatedItems, bool enableAuditing = false )
658703
{
659704
// Triggers when the post-save actions have completed.
660705
var tcsPostSave = new TaskCompletionSource<bool>();
@@ -699,17 +744,17 @@ protected virtual void RockPostSave( List<ContextItem> updatedItems, PersonAlias
699744

700745
if ( item.State == EntityContextState.Detached || item.State == EntityContextState.Deleted )
701746
{
702-
TriggerWorkflows( item, WorkflowTriggerType.PostDelete, personAlias );
747+
TriggerWorkflows( item, WorkflowTriggerType.PostDelete );
703748
}
704749
else
705750
{
706751
if ( item.PreSaveState == EntityContextState.Added )
707752
{
708-
TriggerWorkflows( item, WorkflowTriggerType.PostAdd, personAlias );
753+
TriggerWorkflows( item, WorkflowTriggerType.PostAdd );
709754
}
710755

711-
TriggerWorkflows( item, WorkflowTriggerType.ImmediatePostSave, personAlias );
712-
TriggerWorkflows( item, WorkflowTriggerType.PostSave, personAlias );
756+
TriggerWorkflows( item, WorkflowTriggerType.ImmediatePostSave );
757+
TriggerWorkflows( item, WorkflowTriggerType.PostSave );
713758
}
714759

715760
if ( item.Entity is IEntity entity )
@@ -1075,7 +1120,7 @@ public virtual void BulkInsertWithConditionalCacheUse<T>( IEnumerable<T> records
10751120

10761121
// ensure CreatedDateTime and ModifiedDateTime is set
10771122
var currentDateTime = RockDateTime.Now;
1078-
var currentPersonAliasId = this.GetCurrentPersonAlias()?.Id;
1123+
var currentPersonAliasId = this.GetCurrentPersonAliasId();
10791124

10801125
foreach ( var record in records )
10811126
{
@@ -1146,8 +1191,8 @@ public virtual void BulkInsert<T>( IEnumerable<T> records ) where T : class
11461191
public virtual int BulkUpdate<T>( IQueryable<T> queryable, Expression<Func<T, T>> updateFactory ) where T : class
11471192
{
11481193
var currentDateTime = RockDateTime.Now;
1149-
PersonAlias currentPersonAlias = this.GetCurrentPersonAlias();
1150-
var rockExpressionVisitor = new RockBulkUpdateExpressionVisitor( currentDateTime, currentPersonAlias );
1194+
var currentPersonAliasId = this.GetCurrentPersonAliasId();
1195+
var rockExpressionVisitor = new RockBulkUpdateExpressionVisitor( currentDateTime, currentPersonAliasId );
11511196
var updatedExpression = rockExpressionVisitor.Visit( updateFactory ) as Expression<Func<T, T>> ?? updateFactory;
11521197
int recordsUpdated = queryable.Update( updatedExpression, batchUpdateBuilder =>
11531198
{
@@ -1192,9 +1237,8 @@ public virtual int BulkDelete<T>( IQueryable<T> queryable, int? batchSize = null
11921237
/// </summary>
11931238
/// <param name="item">The item.</param>
11941239
/// <param name="triggerType">Type of the trigger.</param>
1195-
/// <param name="personAlias">The person alias.</param>
11961240
/// <returns></returns>
1197-
private bool TriggerWorkflows( ContextItem item, WorkflowTriggerType triggerType, PersonAlias personAlias )
1241+
private bool TriggerWorkflows( ContextItem item, WorkflowTriggerType triggerType )
11981242
{
11991243
IEntity entity = item.Entity;
12001244
Dictionary<string, PropertyInfo> properties = null;

Rock/Data/RockBulkUpdateExpressionVisitor.cs

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,16 +31,29 @@ internal class RockBulkUpdateExpressionVisitor : ExpressionVisitor
3131
{
3232
private DateTime _currentDateTime;
3333
private PersonAlias _currentPersonAlias;
34+
private int? _currentPersonAliasId;
3435

3536
/// <summary>
3637
/// Initializes a new instance of the <see cref="RockBulkUpdateExpressionVisitor"/> class.
3738
/// </summary>
3839
/// <param name="currentDateTime">The current date time.</param>
3940
/// <param name="currentPersonAlias">The current person alias.</param>
41+
[Obsolete( "Use RockBulkUpdateExpressionVisitor( DateTime currentDateTime, int? currentPersonAliasId ) instead" )]
42+
[RockObsolete( "18.0" )]
4043
public RockBulkUpdateExpressionVisitor( DateTime currentDateTime, PersonAlias currentPersonAlias )
4144
{
4245
_currentDateTime = currentDateTime;
4346
_currentPersonAlias = currentPersonAlias;
47+
if ( currentPersonAlias != null )
48+
{
49+
_currentPersonAliasId = currentPersonAlias.Id;
50+
}
51+
}
52+
53+
public RockBulkUpdateExpressionVisitor( DateTime currentDateTime, int? currentPersonAliasId )
54+
{
55+
_currentDateTime = currentDateTime;
56+
_currentPersonAliasId = currentPersonAliasId;
4457
}
4558

4659
/// <summary>
@@ -64,9 +77,9 @@ protected override Expression VisitMemberInit( MemberInitExpression node )
6477
}
6578

6679
MemberInfo modifiedByPersonAliasIdMemberInfo = typeof( Rock.Data.IModel ).GetMember( "ModifiedByPersonAliasId" ).FirstOrDefault();
67-
if ( modifiedByPersonAliasIdMemberInfo != null && _currentPersonAlias != null )
80+
if ( modifiedByPersonAliasIdMemberInfo != null && ( _currentPersonAliasId.HasValue || _currentPersonAlias != null ) )
6881
{
69-
currentBindings.Add( Expression.Bind( modifiedByPersonAliasIdMemberInfo, Expression.Constant( _currentPersonAlias.Id ) ) );
82+
currentBindings.Add( Expression.Bind( modifiedByPersonAliasIdMemberInfo, Expression.Constant( _currentPersonAliasId.Value ) ) );
7083
}
7184

7285
node = node.Update( node.NewExpression, currentBindings );

Rock/Model/CMS/PersonalLinkSectionOrder/PersonalLinkSectionOrder.Logic.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ public partial class PersonalLinkSectionOrder
3939
/// <param name="dbContext">The database context.</param>
4040
public void UpdateCache( EntityState entityState, Data.DbContext dbContext )
4141
{
42-
var currentPersonAliasId = dbContext.GetCurrentPersonAlias()?.Id;
42+
var currentPersonAliasId = dbContext.GetCurrentPersonAliasId();
4343
if ( this.PersonAliasId == currentPersonAliasId )
4444
{
4545
// If the current person is the one modifying this (it probably is), update the Session

Rock/Model/CRM/PersonSearchKey/PersonSearchKey.Logic.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ protected override void BuildHistoryItems( Data.DbContext dbContext, DbEntityEnt
113113
caption,
114114
typeof( PersonSearchKey ),
115115
Id,
116-
dbContext.GetCurrentPersonAlias()?.Id,
116+
dbContext.GetCurrentPersonAliasId(),
117117
dbContext.SourceOfChange );
118118
}
119119

Rock/Model/CRM/UserLogin/UserLogin.SaveHook.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ protected override void PreSave()
110110
var isUserNameSensitive = ( entityType?.Guid == Rock.SystemGuid.EntityType.AUTHENTICATION_PIN.AsGuid() ) ? true : false;
111111

112112
// Get the current person to correctly ascribe the deletion / modification.
113-
var currentPersonAliasId = DbContext.GetCurrentPersonAlias()?.Id;
113+
var currentPersonAliasId = DbContext.GetCurrentPersonAliasId();
114114
if ( !isUserNameSensitive )
115115
{
116116
HistoryChanges.AddChange( History.HistoryVerb.Delete, History.HistoryChangeType.Record, "User Login" ).SetOldValue( userLogin.UserName );

Rock/Model/Connection/ConnectionRequest/ConnectionRequest.SaveHook.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,6 @@ internal class SaveHook : EntitySaveHook<ConnectionRequest>
6161
/// </summary>
6262
protected override void PreSave()
6363
{
64-
// Get the current person's alias ID from the current context.
65-
var currentPersonAliasId = DbContext.GetCurrentPersonAlias()?.Id;
66-
6764
HistoryChangeList = new History.HistoryChangeList();
6865
PersonHistoryChangeList = new History.HistoryChangeList();
6966
var connectionRequest = this.Entity as ConnectionRequest;
@@ -154,7 +151,7 @@ protected override void PreSave()
154151
protected override void PostSave()
155152
{
156153
// Get the current person's alias ID from the current context.
157-
var currentPersonAliasId = DbContext.GetCurrentPersonAlias()?.Id;
154+
var currentPersonAliasId = DbContext.GetCurrentPersonAliasId();
158155
var connectionRequest = this.Entity as ConnectionRequest;
159156

160157
// Create and send the change notification message now that the connection request has been saved.

Rock/Model/Core/AttributeMatrixItem/AttributeMatrixItem.Logic.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ protected override void BuildHistoryItems( Data.DbContext dbContext, DbEntityEnt
149149
matrixAttributeCache.Name,
150150
typeof( Attribute ),
151151
matrixAttributeCache.Id,
152-
dbContext.GetCurrentPersonAlias()?.Id,
152+
dbContext.GetCurrentPersonAliasId(),
153153
dbContext.SourceOfChange );
154154
}
155155

Rock/Model/Core/AttributeValue/AttributeValue.Logic.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -426,7 +426,7 @@ protected override void BuildHistoryItems( Data.DbContext dbContext, DbEntityEnt
426426
caption,
427427
typeof( Attribute ),
428428
AttributeId,
429-
dbContext.GetCurrentPersonAlias()?.Id,
429+
dbContext.GetCurrentPersonAliasId(),
430430
dbContext.SourceOfChange );
431431
}
432432

Rock/Model/Core/Auth/Auth.SaveHook.cs

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,7 @@ protected override void PreSave()
4545
authAuditLog.Action = auth.Action;
4646
authAuditLog.ChangeDateTime = RockDateTime.Now;
4747
authAuditLog.SpecialRole = auth.SpecialRole;
48-
var currentPersonAlias = rockContext.GetCurrentPersonAlias();
49-
if ( currentPersonAlias != null )
50-
{
51-
authAuditLog.ChangeByPersonAliasId = currentPersonAlias.Id;
52-
}
48+
authAuditLog.ChangeByPersonAliasId = rockContext.GetCurrentPersonAliasId();
5349

5450
authAuditLogService.Add( authAuditLog );
5551

Rock/Model/Finance/FinancialPersonSavedAccount/FinancialPersonSavedAccount.Logic.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ protected override void BuildHistoryItems( Data.DbContext dbContext, DbEntityEnt
173173
GetNameForHistory( originalModel?.FinancialPaymentDetail ?? FinancialPaymentDetail ),
174174
typeof( FinancialPersonSavedAccount ),
175175
Id,
176-
dbContext.GetCurrentPersonAlias()?.Id,
176+
dbContext.GetCurrentPersonAliasId(),
177177
dbContext.SourceOfChange );
178178
}
179179

0 commit comments

Comments
 (0)