Reputation: 1908
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!
Upvotes: 1
Views: 1127
Reputation: 1908
Thanks to this post EntityFramework Code First - Check if Entity is attached, I create a DbContext extension (as suggested on the link).
public static bool Exists<TEntity>(this DbContext ctx, TEntity entity)
where TEntity : class
{
return ctx.Set<TEntity>().Local.Any(e => e == entity);
}
And it worked nicely!
if (ef.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();
...
...
...
}
I hope this post could help someone with similar problem.
Cheers!
Upvotes: 2