C
C#6mo ago
SWEETPONY

Is it worth to use AsNoTracking in dbset?

I found this:
public class ReadOnlyReadModelDbContext
{
readonly ReadModelDbContext dbContext;
public ReadOnlyReadModelDbContext(ReadModelDbContext dbContext)
{
this.dbContext = dbContext;
}
public IQueryable<Qualification> Qualifications => dbContext.Qualifications.AsNoTracking();
public IQueryable<Function> Functions => dbContext.Functions.AsNoTracking();
public IQueryable<FunctionQualification> FunctionQualifications => dbContext.FunctionQualifications.AsNoTracking();
public IQueryable<Resource> Resources => dbContext.Resources.AsNoTracking();
public IQueryable<Node> Nodes => dbContext.Nodes.AsNoTracking();
public IQueryable<Location> Locations => dbContext.Locations.AsNoTracking();
}
public class ReadOnlyReadModelDbContext
{
readonly ReadModelDbContext dbContext;
public ReadOnlyReadModelDbContext(ReadModelDbContext dbContext)
{
this.dbContext = dbContext;
}
public IQueryable<Qualification> Qualifications => dbContext.Qualifications.AsNoTracking();
public IQueryable<Function> Functions => dbContext.Functions.AsNoTracking();
public IQueryable<FunctionQualification> FunctionQualifications => dbContext.FunctionQualifications.AsNoTracking();
public IQueryable<Resource> Resources => dbContext.Resources.AsNoTracking();
public IQueryable<Node> Nodes => dbContext.Nodes.AsNoTracking();
public IQueryable<Location> Locations => dbContext.Locations.AsNoTracking();
}
In my opinion it doesn't look correct. What do you think?
5 Replies
viceroypenguin
viceroypenguin6mo ago
you can just do:
services.AddDbContext<DbContext>(o =>
o.UseQueryTrackingBehavior(
QueryTrackingBehavior.NoTracking));
services.AddDbContext<DbContext>(o =>
o.UseQueryTrackingBehavior(
QueryTrackingBehavior.NoTracking));
and then when you need them to be tracking you can do _db.Functions.AsTracking() no need to have two different dbcontexts or anything like that
SWEETPONY
SWEETPONY6mo ago
didn't know about that! thanks
Joschi
Joschi6mo ago
Or you just call AsNoTracking() on the query itself, instead of changing the defaults.
Angius
Angius6mo ago
If you .Select() into DTOs — as you should — that alone disables tracking and if you're fetching something without projecting it, that means you're doing some fetch-update-save or fetch-delete-save pattern Where you do want tracking
Joschi
Joschi6mo ago
Interesting, did not know that.