165
votes

There is no Detach(object entity) on the DbContext.

Do I have the ability to detach objects on EF code first?

2

2 Answers

174
votes

If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:

var data = context.MyEntities.AsNoTracking().Where(...).ToList();

As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.

287
votes

This is an option:

dbContext.Entry(entity).State = EntityState.Detached;