Last active
September 16, 2026 20:51
-
-
Save peteraritchie/73e4c177a863cf3a97606089e62f9a8c to your computer and use it in GitHub Desktop.
Extension method to get #entity-framework shadow property entry using the try pattern in #csharp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System.Diagnostics.CodeAnalysis; | |
| using Microsoft.EntityFrameworkCore.ChangeTracking; | |
| namespace Common; | |
| public static class EntityEntryExtensions | |
| { | |
| extension<TEntity>(EntityEntry<TEntity> entityEntry) where TEntity : class | |
| { | |
| /// <summary> | |
| /// Get a PropertyEntry for a named shadow property for a given EntityEntry | |
| /// </summary> | |
| /// <typeparam name="TProperty">The shadow properties type.</typeparam> | |
| /// <param name="name">Name of the shadow property.</param> | |
| /// <param name="propertyEntry">The resulting PropertyEntry or null if nonexistent.</param> | |
| /// <returns><code>true</code> if successful, <code>false</code> otherwise.</returns> | |
| public bool TryGetPropertyEntry<TProperty>(string name, | |
| [NotNullWhen(true)]out PropertyEntry<TEntity, TProperty>? propertyEntry) | |
| { | |
| if (entityEntry.Properties.Any(e => e.Metadata.Name == name)) | |
| { | |
| propertyEntry = entityEntry.Property<TProperty>(name); | |
| return true; | |
| } | |
| propertyEntry = null; | |
| return false; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment