How do I verify that an entity is tracked with Entity framework Core 2.0.3?

Asked

Viewed 38 times

0

In my repository, I need to create a function that returns a "boolean" informing me if an Entity is being "Tracked". I need to do this, because when I do an "update" of the same entity more than once, within a transaction, the Entity framework bursts an error stating that the entity is being tracked. I tried to check, but the return is always being false. Does anyone know a way to check this?

public bool IsTracked(TEntity obj)
{
    var teste = Db.Entry(obj).State;
    return teste == EntityState.Modified;
}

COMPLETE REPOSITORY:

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
    protected readonly RetaguardaContext Db;
    protected readonly DbSet<TEntity> DbSet;

    public Repository(RetaguardaContext context)
    {
        Db = context;
        DbSet = Db.Set<TEntity>();
    }

    public virtual void Add(TEntity obj)
    {
        DbSet.Add(obj);
    }

    public virtual TEntity GetById(int id)
    {
        return DbSet.Find(id);

        //tentativa
        //var entity = DbSet.Find(id);
        //Db.Entry(entity).State = EntityState.Detached;
        //return entity;
    }

    public virtual IQueryable<TEntity> GetAll(bool @readonly = false)
    {
        return @readonly ?
            DbSet.AsTracking() :
            DbSet;
    }

    public virtual void Update(TEntity obj)
    {
        DbSet.Update(obj);
    }

    public virtual void Remove(int id)
    {
        var obj = DbSet.Find(id);
        if (obj != null)
            DbSet.Remove(obj);
    }

    public int SaveChanges()
    {
        return Db.SaveChanges();
    }

    public void Dispose()
    {
        Db.Dispose();
        GC.SuppressFinalize(this);
    }

    public void Remove(params object[] keyValues)
    {
        var obj = DbSet.Find(keyValues);
        if (obj != null)
            DbSet.Remove(obj);
    }

    public TEntity GetByIds(params object[] keyValues)
    {
        return DbSet.Find(keyValues);
    }

    public int GetMax(Expression<Func<TEntity, int>> select)
    {
        return DbSet.Select(select).Max();
    }       

    public bool IsTracked(TEntity obj)
    {
        var teste = Db.Entry(obj).State;
        return teste == EntityState.Modified;
    }

    public IQueryable<TEntity> GetAll(Expression<Func<TEntity, bool>> predicate)
    {
        return DbSet.AsTracking().Where(predicate);
    }
}

1 answer

-2


could test that way.

public bool IsTracked(TEntity obj)
{
   var response = Db.Entry(obj).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
   SaveChanges();
   return response;
}
  • Thanks for the @Matheus tip!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.