I am writing a Blazor (server side) app and have come to the conclusion that I want change tracking on for CrUD operations and off for cRud operations.
Should I create two DbContext classes, one that returns a DbContext with change tracking on and the other with it off? This would have both pointing to the same DB.
Or is it better to have a single DbContext class that has change tracking on. And then when I need data just to display it, I use context.Books.AsNoTracking()... to turn it off for that query.
Why
I figure change tracking makes sense for CrUD operations for two reasons. First, because that will avoid bugs due to my forgetting to call Add()
someplace where needed. Second, because Update()
is heavy handed re-writing everything while change tracking only writes what has changed.
I figure no tracking makes sense for cRud operations because it removes the overhead of change tracking when nothing is going to change. And it's safe as I will do this only for web pages that are essentially read only views of information.
So keep it safe & simple while gaining performance for the cRud case.
Two DbContext
I haven't tried it yet but I assumed I can make the following call and somehow then select the context I want. I don't know if this is possible and that's part of what I'm asking here.
builder.Services.AddDbContextFactory<LouisHoweDbContext>( options =>
options.UseSqlServer( builder
.Configuration
.GetConnectionString("LouisHoweDb")
)
.EnableSensitiveDataLogging()
);
builder.Services.AddDbContextFactory<LouisHoweDbContext>( options =>
options.UseSqlServer( builder
.Configuration
.GetConnectionString("LouisHoweDb")
)
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
.EnableSensitiveDataLogging()
);