Neophyte.net
Neophyte.net

Reputation: 561

Is it possible to Add in DbContext without tracking in .NET Core

Is it possible to do Add, AddAsync, Update etc in .NET Core without the entity being tracked afterwards without having to write code to specifically detach the context from tracking the entity?

// select, its possible to do no trackiing
var audit = _dbContext.Audit.First().AsNoTracking();

// doing an add or update, audit is now tracked unless it's detached
_dbContext.Audit.Add(audit);
int rows = _dbContext.SaveChanges();
_dbContext.Entry(audit).State = EntityState.Detached;

I ask this because I have a windows service that consumes RabbitMq messages and writes to the database. RabbitMq receives messages via an event handler. So the database essentially becomes a singleton even though its added as transient. I could create a new db context each time. but it seems overkill. Or is there a better way?

Upvotes: 6

Views: 7345

Answers (1)

Getson Cela
Getson Cela

Reputation: 411

You shouldn't have singleton DbContext because it is not thread safe. You can take a look at this blog post for different approaches of managing DbContext: https://mehdi.me/ambient-dbcontext-in-ef6/

Upvotes: 3

Related Questions