0
services.AddDbContextPool<SecurityDBContext>(options =>
                options.UseSqlServer(GlobalConfig.Configuration["ConnectionStrings:DefaultConnection"],
                b => b.UseQuerySplittingBehavior(QuerySplittingBehavior.SingleQuery))
        );

This is how I added dbcontext,I used AddDbContextPool so the instance will be use over and over again for performance.

db.Entry(new AdminBlockClientConfig()
        {
            ActionId = input.aid.ToLongReturnZiro(),
            MaxValue = input.value.ToIntReturnZiro(),
            IsActive = input.isActive.ToBooleanReturnFalse(),
            SiteSettingId = siteSettingId.ToIntReturnZiro()
        }).State = EntityState.Added;
        db.SaveChanges();

This is my code for adding new entity.

 readonly SecurityDBContext db = null;
    static List<AdminBlockClientConfig> AdminBlockClientConfigs = null;

    public AdminBlockClientConfigService(SecurityDBContext db)
    {
        this.db = db;
    }

This is my service constructor

services.AddScoped<IAdminBlockClientConfigService, AdminBlockClientConfigService>();

And this is my service injection config

The problem:

I don't have any validation for ActionId inside of my add new entity so if the user posts -1 for ActionId the entity will not be insert into SQL Server (relation problem) the system raises an exception and everything is as planed but the main problem is that one of the instance of SecurityDBContext become corrupted and I am no longer be able to call save change on that instance because the entity instance is still attached to dbcontext.

What is need:

It would be great if I can detach the entity after an error automatically so I can save the context. I know how to detach entity from dbcontext, I need to its happen automatically (there is so many validation need to be added to project and I can not put time for those validation and if I put that time there will be high change of missing some place and its will be bug that can destroy my application and for performance I don't like to change the way I added dbcontext instance).

Thanks for your time.

edited: AddDbContextPool is not the problem, if one of my services add invalid data to dbcontext the other services can not use that dbcontext

  • 1
    If you get a context from the pool, it's already cleared. I don't understand your problem. Just get a new context and redo the whole process except the invalid entity object. – Gert Arnold Jun 29 '22 at 07:13
  • How do you get the `db` variable you are using? Do you ask the pool for it each time you call your method or do you ask for it once per service per request? – Francesco D.M. Jun 29 '22 at 08:14
  • if you use AddDbContextPool the dependency injection will create for example 100 dbcontext and use them for inject. create new instance of dbcontext is expensive this is how its help improve performance and there will be a 1% change that the dbcontext that going to be inject in my service will be the corrupted dbcontext per each request. i am using .net core 6 – testApplication Insurance Jun 29 '22 at 08:16
  • I am using dependency injection – testApplication Insurance Jun 29 '22 at 08:18
  • I edited my question and add more info can you check it out – testApplication Insurance Jun 29 '22 at 08:27
  • I understand how the pool works. What I think might be going on is that you are calling multiple times the same service (which I think you registered as a Scoped service) so between the multiple calls in the same request the context is shared. Is this correct? – Francesco D.M. Jun 29 '22 at 08:47
  • There *is* no corrupted context if you get it from the pool. As I said, EF clears it before returning it from the pool. You should run your code without context pooling and see if the issue persists. – Gert Arnold Jun 29 '22 at 08:50
  • It's not clear where/when this code `db.Entry(new AdminBlockClientConfig()` runs. – Gert Arnold Jun 29 '22 at 08:54
  • dear Francesco D.M PLZ trust me, i am not using one service multiple times, it is simple request and simple insert in database, – testApplication Insurance Jun 29 '22 at 10:09
  • dear Gert Arnold let me explain with one example, there is 10 service that inject per each request let call them userService, roleService, fileManager and..... after one website request, one instance of all of them will be created and all of them using SecurityDBContext with this config: AddDbContextPool . now we have 10 service for one web request and one instance of SecurityDBContext . know if for example userService add invalid data to DbContext the other service for example roleService can not call save change because we have one instance of SecurityDBContext and there is invalid – testApplication Insurance Jun 29 '22 at 10:18
  • ----- entity attached to it, and when you call save change all changes in the dbcontext will be effected to sql server – testApplication Insurance Jun 29 '22 at 10:21
  • its run one time per each request, i didn't do any thing wired. – testApplication Insurance Jun 29 '22 at 10:25
  • Gert Arnold :You should run your code without context pooling and see if the issue persists. answer: yes its persists. this is what i used : services.AddDbContext(options => options.UseSqlServer(GlobalConfig.Configuration["ConnectionStrings:DefaultConnection"], b => { b.UseQuerySplittingBehavior(QuerySplittingBehavior.SingleQuery); }) ); – testApplication Insurance Jun 29 '22 at 10:42
  • I edited my question can you PLZ check it out – testApplication Insurance Jun 29 '22 at 10:48
  • Standard life span when using `AddDbContext` (or pool) is per scope. Which means that each service has the same context. It seems to me that if you need 10 services to process one use case you need to split it up. Maybe something like adding users first, then roles, then user-roles, etc. – Gert Arnold Jun 29 '22 at 11:25
  • public override int SaveChanges() { try { return base.SaveChanges(); } catch (DbUpdateException ex) { if (ex.Entries != null) foreach (var entry in ex.Entries) this.Entry(entry.Entity).State = EntityState.Detached; throw; } catch (Exception) { throw; } } – testApplication Insurance Jul 02 '22 at 04:30
  • above code solved my problem – testApplication Insurance Jul 02 '22 at 04:30

0 Answers0