Efcore: Find() with AsNoTracking()

Created on 3 Jul 2015  路  4Comments  路  Source: dotnet/efcore

I've checked the Find() method on DbSet class can not be used together with AsNoTracking().
There are numerous situations where I need to use the Find() and do not put the object returned in context.
I would like to suggest this functionality within the Entity Framework.

Portugues:
Estive verificando que o m茅todo Find() da classe DbSet n茫o pode ser usado junto com o AsNoTracking().
Existem inumeras situa莽玫es em que preciso usar o Find() e n茫o colocar o objeto retornado dentro do contexto.
Gostaria de sugerir essa funcionalidade dentro do Entity Framework.

Most helpful comment

AsNoTracking doesn't really make sense for Find since one of the key features of find is that it will return the already tracked version of the entity without hitting the database if it is already in memory. If you want to load an entity by key without tracking it then use Single.

All 4 comments

AsNoTracking doesn't really make sense for Find since one of the key features of find is that it will return the already tracked version of the entity without hitting the database if it is already in memory. If you want to load an entity by key without tracking it then use Single.

if i use
```C#
if (lstemployeeRepository.Find(employee.LstEmployeeId)==null)
return NotFound();

        if (!ModelState.IsValid)
        {
            return new UnprocessableEntityObjectResult(ModelState);
        }

        lstemployeeRepository.Update(employee);

```
Getting error "System.InvalidOperationException: 'The instance of entity type 'LstEmployee' cannot be tracked because another instance with the same key value for {'LstEmployeeId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'
"

I'm hitting the same issue.

    var props = typeof(TState).GetProperties();
    var primaryKey = this.sqlStore.Model.GetEntityTypes().Single(et => et.ClrType == typeof(TState)).FindPrimaryKey();

    var keyValues = primaryKey.Properties.Select(p => props.Single(pp => pp.Name == p.Name).GetValue(state)).ToArray();

    var entity = await this.sqlStore.FindAsync<TState>(keyValues);
    if (entity == null)
    {
        this.sqlStore.Add(state);
    }
    else
    {
        this.sqlStore.Update(state);
    }

Now the Update() fails because entity and state have the same value of key (as intended). I cannot really use Single() here as I am relying on the "dynamic/untyped" nature of Find().

@satvik1986 @mrmartan Can you file new issues for the problems you are seeing, including a runnable project/solution or complete code listing that demonstrates the problem?

Was this page helpful?
0 / 5 - 0 ratings