In the below snipped i try to fetch data using Anonymous Projection
and i would like do not track the entities
that is fetched.
Note : i have already gone through existing stack question,yet unable to find a working solution for me
using (var db = new Entities())
{
db.Configuration.LazyLoadingEnabled = false;
db.Configuration.ProxyCreationEnabled = false;
var myprojection = db.Table1
.AsNoTracking()
.Include(gh=>gh.Table2) //Update
.Include(gh=>gh.Table3) //Update
.Select(x => new
{
table1= x,
table2= x.Table2.Where(g => Some Condition),
table3= x.Table3.Where(g=>Some Condition)
})
.ToList();
var result = myprojection.Select(g =>g.table1).FirstOrDefault();
}
When i use
AsNoTracking()
data from the inner tables (table2,3) is lost during the conversion at this linevar result = myprojection.Select(g =>g.table1).FirstOrDefault();
Edit
If i remove
AsNoTracking()
everything works fine.
1) How to use projection
and AsNoTracking
in entity framework correctly ?
2) Any other option to remove tracking of this query?
Is there any possible workarounds?
AsNoTracking(IQueryable)Returns a new query where the entities returned will not be cached in the DbContext or ObjectContext. This method works by calling the AsNoTracking method of the underlying query object.
No-Tracking query using AsNoTracking() extention method The AsNoTracking() extension method returns a new query and returned entities do not track by the context. It means that EF does not perform any additional task to store the retrieve entities for tracking.
You can just call context. Entry(entity). State = EntityState. Detached and it will stop tracking that particular entity.
The approach that you adopt to deleting entities via the DbContext depends on whether the context is currently tracking the entity being deleted or not. In the following example, the entity to be deleted is obtained by the context, so the context begins tracking it immediately.
Use ToList()
for your navigation properties. Note that it will still projekt in the DB. (EF6)
// ..
table2 = x.Table2.Where(g => Some Condition).ToList(),
Update:
With EF4 you probably need to map table2
manually:
table2 = x.Table2.Where(g => CONDITION).Select(x => new {Foo = x.Bar}),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With