Last active
January 2, 2022 17:24
-
-
Save shahabganji/65a63d1e321fde391e304e478b040464 to your computer and use it in GitHub Desktop.
Explore Shadow Properties in EF Core
This file contains 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
private void UpdateTrackingDates() | |
{ | |
var trackingDatesChangedEntries = this.ChangeTracker.Entries() | |
.Where(entry => entry.State == EntityState.Added | |
|| entry.State == EntityState.Modified | |
&& entry.Entity is IHaveTrackingDates | |
); | |
foreach (var entry in trackingDatesChangedEntries) | |
{ | |
if (entry.State == EntityState.Modified) | |
this.Entry(entry).Property("LastUpdatedOn") | |
.CurrentValue = DateTimeOffset.UtcNow; | |
else if (entry.State == EntityState.Added) | |
this.Entry(entry).Property("CreatedOn") | |
.CurrentValue = DateTimeOffset.UtcNow; | |
} | |
} | |
public override int SaveChanges() | |
{ | |
this.UpdateTrackingDates(); | |
return base.SaveChanges(); | |
} | |
public override Task<int> SaveChangesAsync( | |
CancellationToken cancellationToken = new CancellationToken()) | |
{ | |
this.UpdateTrackingDates(); | |
return base.SaveChangesAsync(cancellationToken); | |
} |
This file contains 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
public interface IHaveTrackingDates { } | |
public class Author : ICanBeSoftDeleted , IHaveTrackingDates | |
{ | |
// omitted code | |
} |
This file contains 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
public static void AddTrackingDatesShadowProperties(this ModelBuilder modelBuilder) | |
{ | |
var trackingDatesEntities = | |
typeof(IHaveTrackingDates) | |
.Assembly.GetTypes() | |
.Where( | |
type => typeof(IHaveTrackingDates) | |
.IsAssignableFrom(type) | |
&& type.IsClass | |
&& !type.IsAbstract); | |
foreach (var entity in trackingDatesEntities) | |
{ | |
modelBuilder.Entity(entity) | |
.Property<DateTimeOffset>("CreatedOn") | |
.IsRequired(); | |
modelBuilder.Entity(entity) | |
.Property<DateTimeOffset?>("LastUpdatedOn") | |
.IsRequired(false) | |
.HasColumnName("LastUpdatedAt"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment