Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF: detach vs. eager loading vs. noTracking

I'm a bit confused about the meaning of the followings:

What is the difference between them?

1) AsNoTracking - meaning no dirtiness check. (same as changing EntityState to Detached?)

2) context.Detach(order) - (same as changing EntityState to Detached?)

3) is NoTracking also needed for eager loading?

 creativeWorkshopEntities.Job.MergeOption = MergeOption.NoTracking;
    var q = from c in creativeWorkshopEntities.Job.Include("Files")
            where c.Id == jobId                    
            select c; 

All I want to do is detach the entity

I have a using statement for every request in my BL class.

I cannot detach the entity after filling the cache from the DB

as I still call its properties in the application flow. I guess it will throw runtime exception (objectContext is desposed)

Do you think my logic is correct?

public static Group GetMamData(string stamp, MaMDBEntities maMDBEntities)
{
    Group group = MamDataCacheManager.GetMamData(stamp);
    if (group == null)
    {
        //was not found in the cache
        //check for aveilable test with status 'start' - 1
        group = GetGroupsFromDb(stamp, maMDBEntities);

        if (group != null)
        {
            maMDBEntities.Entry(group).State = EntityState.Detached;
            MamDataCacheManager.InsertMamData(stamp, group);
        }
    }

    //option B: attache a new context
    if (maMDBEntities.Entry(group).State == EntityState.Detached)
    {
        maMDBEntities.Groups.Attach(group);
    }
    return group;
}
like image 460
Elad Benda Avatar asked Apr 18 '26 21:04

Elad Benda


1 Answers

One of the main functions of an ORM (EF) is Change Tracking: keep track of changed/deleted/new entities so that the proper SQL can be generated.

But Change tracking is not free, it requires quite a bit of some and space. So when you do not need it, use AsNoTracking as an optimization.

1) AsNoTracking - meaning no dirtiness check. (same as changing EntityState to Detached?)

The end result is the same but it is cheaper to load it without tracking than to turn it off later.

2) context.Detach(order) - (same as changing EntityState to Detached?)

Basically, Yes. But I think calling Detach() is the proper way.

3) is NoTracking also needed for eager loading?

No, I don't think so.

like image 137
Henk Holterman Avatar answered Apr 20 '26 11:04

Henk Holterman