//This function shows you then Entities that the EF Core failed to Delete
public class SuppressDeleteConcurrencyInterceptor: ISaveChangesInterceptor
{
public ValueTask<IntercetpionResult> ThrowingConcurrencyExceptionAsync(
ConccurrencyExceptionEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default
) => eventData.Entries.All(e => e.State == EntityState.Deleted)? new ValueTask<InterceptionResult>(InterceptionResult.Suppress()):new(result);
}
//Dont forget to add the Interceptors to the db Context OnConfiguring
protected override void OnConfiguring(DbContextOptionBuilder optionBuilder)
=> optionBuilder.AddInterceptors(
new LoggerInjectionInterceptor(),
new SuppressDeleteConcurrencyInterceptor())
_cache.GetOrAdd(key,AFunctionToCheckIfKeyValueIsNotFound); //If value is null the GetOrAdd Function executes the function below and then caches values.
//define the function to execute if Value is not found
private ValueToReturn AFunctionToCheckIfKeyValueIsNotFound(){
//Do Something
//return value;
}?
3. DbSet is initialized every time you create DbContext, when you do var db = new DbContext() the DbSet is compiled again. However, if you don't want the DbSet to be Compiled every time you request a new Database Context then you might want to look into Connection Pooling.
public DbSet<Blog> Blogs => Set<Blogs>();//This is nullable, the Compiler knows it.
- The other option is declaring the DbSet as below, which I prefer because it will give you some performance:
- Keep in mind though, that when you use the pattern above, you will be calling the Same Instance over and over.
If you use the code and the pattern above, it will use the cached Set Objects
var contextPool = new PooledDbContextFactory<myDbContext>(options);//Everytime you use the contextPool it will reuse the same object
//You could use dbPooling in the DI by using
services.AddDbContextPool<MyDbContext>(options);?
services.AddDbContext<dbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")).EnableSensitiveDataLogging().EnableDetailedErrors().LogTo(Console.WriteLine,LogLevel.Information), ServiceLifetime.Transient);
?
Thank you, this is great.
Marry said:
What is EF Core?