How to Deattach/Not Track Entity after Add/Update/Remove in EF Core 3

Viewed 2372

In Our Project we are using EF Core 3.1 , as it is generated Entity as POCO so we are using these POCO as models to be used in Controller,BAL and DAL (DAL is of Unit of Work and Respository). During DB Context registration in Startup file we have marked DB context no trackable.

services.AddDbContext<DBContext>(options =>
            options.UseSqlServer(ConfigurationHandler.AppSettings.DBConnection).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)

So now we are looking a way to keep these models independent means if we are using these models to add/update data in DAL(Repository) then this should to be not tracked even after save,update and delete.

 Student getData = await Repository.GetEntityAsync(id).ConfigureAwait(false);

 getData.Name = "Update With Repository Method";
 Repository.Update(getData);
 getData.Name = "Modify entity after Repository Update Method.";
 await unitOfWork.CommitAsync().ConfigureAwait(false);

In above method name value saved in DB is "Modify entity after Repository Update Method" but we want it only "Update With Repository Method". So if we call update method then this model(Student) should not be trackable.

Update Method Implementation in Repository

 public virtual void Update(TEntity entity)
    {
       DbContext.Entry(entity).State = EntityState.Modified;
    }

Commit Method Implementation in Unit of Work :

public async Task<bool> CommitAsync()
    {
        try
        {
            await DbContext.SaveChangesAsync();
            return true;
        }
    }
0 Answers
Related