Is there a way to check if the entity was loaded using AsNoTracking() or not?
As you know, the following code will not work for entity loaded using AsNoTracking().
ef.Entry(db).Collection(p => p.tblProducts).Load();
ef.Entry(db).Collection(p => p.tblOrders).Load();
...
...
...
Therefore, if the entity "db" was loaded using AsNoTracking() then I will do the following for loading its children.
db.tblProducts = ef.tblProducts.AsNoTracking().Where(x => x.WarehouseId == db.WarehouseId).ToList();
db.tblOrders = ef.tblOrders.AsNoTracking().Where(x => x.WarehouseId == db.WarehouseId).ToList();
...
...
...
I know it may not be a good approach, but if entity "db" was loaded using AsNoTracking(), then I know that its children do not need to be tracked too.
The question is, how to find out if the entity (that passed in the function) was loaded using AsNoTracking() or not.
POSSIBLE SOLUTION
I found this post here EntityFramework Code First - Check if Entity is attached, someone post the answer like this
public bool Exists<T>(T entity) where T : class
{
return this.Set<T>().Local.Any(e => e == entity);
}
So, can I use
if (Exists(db))
{
ef.Entry(db).Collection(p => p.tblProducts).Load();
ef.Entry(db).Collection(p => p.tblOrders).Load();
...
...
...
}
else
{
db.tblProducts = ef.tblProducts.AsNoTracking().Where(x => x.WarehouseId == db.WarehouseId).ToList();
db.tblOrders = ef.tblOrders.AsNoTracking().Where(x => x.WarehouseId == db.WarehouseId).ToList();
...
...
...
}
What do you think?
Thanks!