diff --git a/EntityFrameworkCore.Console/Program.cs b/EntityFrameworkCore.Console/Program.cs index 6849369..1893054 100644 --- a/EntityFrameworkCore.Console/Program.cs +++ b/EntityFrameworkCore.Console/Program.cs @@ -22,6 +22,23 @@ context.Database.EnsureCreated(); // Rather than raise: "System.InvalidOperationException: Sequence contains no elements." // var firstCoach = await context.Coaches.FirstOrDefaultAsync(); +async Task SoftDeleteLeague() +{ + var league = context.Leagues.Find(1); + league.IsDeleted = true; + + context.SaveChanges(); + + // This is rather cumbersome. Instead, use a query filter. See League configuration. + //var leagues = context.Leagues.Where(l => !l.IsDeleted).ToList(); + + // This now gets all leagues, with query filters applied. + var leagues = context.Leagues.ToList(); + + // You can also ignore them, if you want in a specific case. + leagues = context.Leagues.IgnoreQueryFilters().ToList(); +} + async Task ConcurrencyCheckExample() { var team = context.Teams.Find(1); diff --git a/EntityFrameworkCore.Data/Configurations/LeagueConfiguration.cs b/EntityFrameworkCore.Data/Configurations/LeagueConfiguration.cs index 93782e0..56bc936 100644 --- a/EntityFrameworkCore.Data/Configurations/LeagueConfiguration.cs +++ b/EntityFrameworkCore.Data/Configurations/LeagueConfiguration.cs @@ -8,6 +8,10 @@ public class LeagueConfiguration : IEntityTypeConfiguration { public void Configure(EntityTypeBuilder builder) { + // This query filter will be always applied. + // Note that you should call HasQueryFilter only once, otherwise the filter is overwritten. + builder.HasQueryFilter(l => l.IsDeleted == false); + builder.HasData( new League { Id = 1, Name = "Local League", CreatedDate = new DateTime(2025, 4, 6, 17, 7, 27, 33)}, new League { Id = 2, Name = "National League", CreatedDate = new DateTime(2025, 4, 6, 17, 7, 27, 33)},